Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 508
jalv1039 Avatar asked Nov 24 '11 10:11

jalv1039


People also ask

How do I know if I have extras intent?

Use the Intent. hasExtra(String name) to check if an extra with name was passed in the intent. Also, use Intent. getStringExtra(String name) directly on the intent to handle the NullPointerException if no extras were passed.

How do I set extras intent?

Use the Intent bundle to add extra information, like so: Intent i = new Intent(MessageService. this, ViewMessageActivity. class); i.


2 Answers

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.

like image 149
Michal Kottman Avatar answered Oct 03 '22 23:10

Michal Kottman


Well, I had similiar problem. in my case the null point exception was happen when I checked if my bundle.getString() was equall to null.

here is how IN MY CASE I solved it:

Intent intent = getIntent();             if(intent.hasExtra("nomeUsuario")){         bd = getIntent().getExtras();         if(!bd.getString("nomeUsuario").equals(null)){             nomeUsuario = bd.getString("nomeUsuario");         }     } 
like image 43
JúlioCézar Avatar answered Oct 04 '22 01:10

JúlioCézar