4

I have one activity calling another. But it keeps giving me the error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference".

Calling activity:

Intent intent1 = new Intent (this, buisnessProfileEdit.class);
Bundle data1 = new Bundle();
data1.putString("Restaurant Username",restaurantUsername);
startActivity(intent1);

Called activity:

Intent intentReceived = getIntent();      
Bundle data = intentReceived.getExtras();
restaurantUsername = data.getString("Restaurant Username");

Can someone help me out why this is happening?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
smart_cookie
  • 85
  • 2
  • 4
  • 12

3 Answers3

4

The real problem is that you are missing to pass the bundle via intent:

intent1.putExtras(data1);

try this:

Intent intent1 = new Intent (this, buisnessProfileEdit.class);
Bundle data1 = new Bundle();
data1.putString("Restaurant Username",restaurantUsername);
intent1.putExtras(data1);
startActivity(intent1);

even you will add a validation for this in your Called activity:

Intent intentReceived = getIntent();      
Bundle data = intentReceived.getExtras();
if(data != null){
     restaurantUsername = data.getString("Restaurant Username");
}else{
     restaurantUsername = "";
}

Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

You can´t invoke the method getString() because your bundle is null!

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
4

Another much simpler and less verbose option is to add and get the extras from the intent itself.

In the calling activity:

Intent intent = new Intent (this, CalledActivity.class);
intent.putExtra("FOO", foo);

In the called activity:

Bundle extras = getIntent().getExtras();
String foo = extras.getString("FOO");
Mig82
  • 4,856
  • 4
  • 40
  • 63
2

You have to add the extras to the actual Intent:

Intent intent1 = new Intent (this, buisnessProfileEdit.class);
Bundle data1 = new Bundle();
data1.putString("Restaurant Username",restaurantUsername);
intent1.putExtras(data1);
startActivity(intent1);

(PS: you have a typo in buisnessProfileEdit.)

CounterFlame
  • 1,612
  • 21
  • 31