Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 911
smart_cookie Avatar asked Jan 06 '23 05:01

smart_cookie


2 Answers

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");
like image 102
Mig82 Avatar answered Mar 17 '23 20:03

Mig82


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!

like image 41
Jorgesys Avatar answered Mar 17 '23 19:03

Jorgesys