Search code examples
androidandroid-activityandroid-intentbundle

Check if extras are set or not


Is there any way to check if an extra has been passed when starting an Activity?

I would like to do something like (on the onCreate() in the Activity):

    Bundle extras = getIntent().getExtras();
    String extraStr = extras.getString("extra");

    if (extraStr == null) {
        extraStr = "extra not set";
    }

But this is throwing a java.lang.NullPointerException.

Thank you.


Solution

  • Use the Intent.hasExtra(String name) to check if an extra with name was passed in the intent.

    Example:

    Intent intent = getIntent();
    
    if (intent.hasExtra("bookUrl")) {
        bookUrl = b.getString("bookUrl");
    } else {
       // Do something else
    }
    

    Also, use Intent.getStringExtra(String name) directly on the intent to handle the NullPointerException if no extras were passed.