I have this code that checks for a value of an extra in an Intent on an Activity that is called from many places in my app:
getIntent().getExtras().getBoolean("isNewItem")
If isNewItem isn't set, will my code crash? Is there any way to tell if it's been set or not before I call it?
What is the proper way to handle this?
As others have said, both
getIntent()
andgetExtras()
may return null. Because of this, you don't want to chain the calls together, otherwise you might end up callingnull.getBoolean("isNewItem");
which will throw aNullPointerException
and cause your application to crash.Here's how I would accomplish this. I think it's formatted in the nicest way and is very easily understood by someone else who might be reading your code.
You don't actually need the call to
containsKey("isNewItem")
asgetBoolean("isNewItem", false)
will return false if the extra does not exist. You could condense the above to something like this:You can also use the
Intent
methods to access your extras directly. This is probably the cleanest way to do so:Really any of the methods here are acceptable. Pick one that makes sense to you and do it that way.
getIntent()
will returnnull
if there is noIntent
so use...You can do this:
It will not crash unless until you use it! You don't have to get it if it exists but if you try, for some reason, to use a an "extra" which doesn' exists your system will crash.
So, try o do something like:
This way you make sure your app won't crash. (and make sure you have a valid
Intent
:))The problem is not the
getBoolean()
but thegetIntent().getExtras()
Test this way:
by the way, if
isNewItem
doesn't exist, it returns de default vaulefalse
.Regards.