-4

I was trying to make a basic intent from one activity to another but it crashes as soon as the button "next is clicked ".

    package com.example.aditya.myapplication;

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;

    public class MainActivity extends AppCompatActivity {
        private Button next;
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            next = (Button) findViewById(R.id.toNextActivity1);
            next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(v.getContext(), qu1.class);
                    startActivity(i);
                }
            });
        }
    }

That's the java code . the activity_main.xml is this

<ImageView
    android:id="@+id/hello"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@mipmap/ic_launcher"
    android:scaleType="center"
    android:layout_marginTop="104dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

<Button
    android:id="@+id/toNextActivity1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorAccent"
    android:text="Play "
    android:layout_marginBottom="79dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@id/hello"
    android:layout_toEndOf="@id/hello" />

Logcat

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aditya.myapplication/com.example.a‌​ditya.myapplication.‌​qu1}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnCli‌​ckListener)' on a null object reference
thijs
  • 3,425
  • 1
  • 25
  • 46

3 Answers3

1

Change v.getContext() to MainActivity.this

next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, qu1.class);
            startActivity(i);
        }
    });
tahsinRupam
  • 5,820
  • 1
  • 15
  • 33
Komal12
  • 3,119
  • 4
  • 13
  • 25
0

Under the

    private Button next;

write

    Activity activity;

inside

    onCreate(){
    activity = this;

    }

then inside onClick

startActivity(new Intent(activity,qu1.class);

this shud solve your problem.

shekhar g h
  • 959
  • 1
  • 7
  • 11
0
  1. May be you donot have add qu1.class activity to the manifest file.
  2. Change v.getContext to MainActivity.this
Ncit Cosmos
  • 1,504
  • 1
  • 13
  • 27