user1884872
user1884872

Reputation: 197

How to check existence Extras in Intent

When I try to get Extras, I get Fatal Eroorr

try{
        Sdacha=getIntent().getExtras().getString("Sdacha");
        }
        catch(NullPointerException e){}

How can I check existence Extras?

Upvotes: 3

Views: 7080

Answers (4)

Andro Selva
Andro Selva

Reputation: 54322

Try this,

if(getIntent().getExtras().containsKey("Sdacha"))
        {
        String  preview=getIntent().getExtras().getString("Sdacha");

        }

EDIT

Also as Evos suggested, one more layer of Null check can also be added to the above code.If you are sure that the extras will not be null, then the above approach is good. If not follow the below one.

 if(getIntent().getExtras()!=null)
        {
        if(getIntent().getExtras().containsKey("Sdacha"))
        {
        String  preview=getIntent().getExtras().getString("Sdacha");
        }
        }

Upvotes: 15

galex
galex

Reputation: 3319

To prevent this from happening, I like to encapsulate my calls into a static startActivity method, the same pattern as the newInstance() in fragments:

public static void startActivity(Activity activity, int param, int flags){
    Intent intent = new Intent(activity, MainActivity.class);
    intent.setFlags(flags);
    intent.putExtra(PARAM, param);
    activity.startActivity(intent);
}

And of course if you use this method from other activities, you'll never have a NPE.

Upvotes: 0

TieDad
TieDad

Reputation: 9929

 Bundle bundle = getIntent().getExtras();
 if (bundle != null) {
      String preview = bundle.getString("Sdacha");
      if (preview != null) {
          // do anything  .....
      }
 }

Upvotes: 1

Evos
Evos

Reputation: 3915

It's easy just check that Extras is not null before getting something from it:

if (getIntent().getExtras() != null){
     Sdacha=getIntent().getExtras().getString("Sdacha");
}

Upvotes: 3

Related Questions