I always get a java.lang.NullPointerException
when retrieve the data from my MainActivity
to my second Activity
.
This from my MainActivity
:
Intent i = new Intent(MainActivity.this,ScanActivity.class);
i.putExtra("isConnected", String.valueOf(isConnected));
i.putExtra("serverIP", serverIP);
startActivity(i);
And here's where I get the NullPointerException
:
Intent extras = getIntent();
public String isConnected = extras.getStringExtra("isConnected");
public String serverIP = extras.getStringExtra("serverIP");
Is my code wrong or is there something else that causes it to be null
?
You cannot get Intent
until SecondActivity
is instantiated. It's the reason for NPE
. Move the code inside of the SecondActivity
's onCreate()
method body.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Intent extras = getIntent();
String isConnected = extras.getStringExtra("isConnected");
String serverIP = extras.getStringExtra("serverIP");
}