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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With