Error: NullPointerException to null object reference (Android)

0

I have a project in Android in which I send the value of a variable from Adapter to Activity like this:

public void onClick(View v) {
Intent inicioIntent = new Intent(context, Activity2.class);
inicioIntent.putExtra("idU", idUser);
context.startActivity(inicioIntent);}

And in the Activity I receive it like this:

protected void onCreate(Bundle savedInstanceState) {
idGestor = intent.getExtras().getString("idG");}

Then the Activity happened to Activity2 , but when I return the app stops and it marks me an error just in the line where I receive the value of the variable.

  

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

I guess you mark it because I'm not sending the value from Activity2 to Activity , but from Adapter to Activity strong>, but that value is supposed to exist already.

    
asked by Geek 13.09.2018 в 19:48
source

2 answers

0

The only thing you should do is these two steps:

1.- Validate that the parameter you pass is not null since when going to another activity I assume that you execute the method finish (), then every time you return to this activity it tries to consume this variable and as this null, it will generate error .

You can validate by placing:

protected void onCreate(Bundle savedInstanceState) {

   Bundle bundle = this.getIntent().getExtras();
   if(bundle !=null){
      idGestor = bundle.getString("idG");  
   } 
}

2.- You must send from the activity2 in the onback event the idG parameter

@Override
 public void onBackPressed() {
   Intent intent = new Intent(Activity2.this, Activity.class);
   intent.putExtra("idG", idG);
   startActivity(intent)
   finish();
 }

3.- Something I'm not sure about is that in your adapter method you call the parameter: idU

public void onClick(View v) {
Intent inicioIntent = new Intent(context, Activity2.class);
inicioIntent.putExtra("idU", idUser);
context.startActivity(inicioIntent);}

But in your activity2 you want to retrieve the parameter with the name idG

protected void onCreate(Bundle savedInstanceState) {
     idGestor = intent.getExtras().getString("idG");
}

Should not that be the case if it were the case in reality?

protected void onCreate(Bundle savedInstanceState) {
idGestor = intent.getExtras().getString("idU");}
    
answered by 13.09.2018 / 21:11
source
1

In MainActivity2 you must do the following, add super.onCreate(savedInstanceState); and also validate the receipt of bundle :

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 Bundle parametros = this.getIntent().getExtras();
 if(parametros !=null){
    idGestor = parametros.getString("idG");  
 } 

}
    
answered by 13.09.2018 в 20:32