0

So i have intent that require some extras,but i was thinking is it possible to open it without passing extras and not getting null pointer?

EDIT: I have activity A and activity B. When i press button im passing few strings as extras to activity B. If its not passed,I will get null pointer and app will crash. What i want is, is it possible to check if there is extras passed,and if its passed to get them,if its not passed continue without it and not get null pointer error?

  • 1
    Possible duplicate of [How do I tell if Intent extras exist in Android?](https://stackoverflow.com/questions/13408419/how-do-i-tell-if-intent-extras-exist-in-android) – udit7395 Mar 11 '18 at 12:35

2 Answers2

0

Yes, it is possible to check it. You need to use Intent.hasExtra(String name) where name is the name of the variable you want to check whether it was passed or not. For example: you place inside Intent string called firstName and then you want to use it in another activity. So here's the code you should place in the second activity:

if(Intent.hasExtra("firstName")) //Intent.hasExtra() return true or false
{
String firstName = Intent.getStringExtra("firstName");
//place here code you want to execute if intent contains firstName
}
else
{
//place here code you want to execute if intent does not contain firstName
}

Related question: Check if extras are set or not

BigRedChick
  • 79
  • 1
  • 7
0

Try this code

in A.java:

Intent intent=new Intent(A.this,B.class);
  intent.putExtra("data","my custom data here");
  startActivity(intent);

in B.java:

String data;
  if (getIntent().hasExtra("data") && getIntent().getStringExtra("data")!=null){ //add a check like that
     data=getIntent().getStringExtra("data");
  }else{
        //add your condition when data parameter is not there or null
  }