Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null pointer exception in intent

I'm trying to call an Activity but it shows a null pointer exception on line 17. I have just started learning Android Studio. Please help me out with this problem, and also explain where I'm going wrong.

public class activity2 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        Button B2 = (Button) findViewById(R.id.B2);
        B2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent ladoo = new Intent(activity2.this,MainActivity.class);
                startActivity(ladoo);
                finish();
            }
        });
        super.onCreate(savedInstanceState);
    }
}
like image 266
Panda Avatar asked May 01 '26 14:05

Panda


1 Answers

In addition to the problem of the super.onCreate() placement, the problem is that you're not calling SetContentView(), so there is no active inflated view with which to reference your Button object.

public class activity2 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState); //add this here
        setContentView(R.layout.activity_activity2); //reference whatever the layout.xml file is named for this Activity

        Button B2 = (Button) findViewById(R.id.B2);
        B2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent ladoo = new Intent(activity2.this,MainActivity.class);
                startActivity(ladoo);
                finish();
            }
        });
        //super.onCreate(savedInstanceState); //remove from here
    }
}

See Documentation Here

like image 74
Daniel Nugent Avatar answered May 04 '26 03:05

Daniel Nugent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!