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.
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.
Use the Intent bundle to add extra information, like so: Intent i = new Intent(MessageService. this, ViewMessageActivity. class); i.
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.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With