Proper way to handle Android Studio's NullPointerException lint warning
Solution 1
I doubt this question can be answered conclusively, as it's a matter of opinion. Or at least I believe so -- an opinion too. :)
I understand you want "0 warnings" (a very laudable goal) but there's probably not a "one size fits all" issue. That said...
Things I believe you should not do:
- Use assert. While you can add an assert statement, Dalvik ignores them. You can configure an emulator to use them if you want, but not a real device (see Can I use assert on Android devices?). So while it would possibly remove the warning, it's useless in practice.
- Have the method throw
NullPointerException
. This would be a bad idea, generally. In this case, since you're probably overridingonOptionsItemSelected()
, it's not even possible.
Checking for (variable != null)
is generally the best approach. What to do if it is, though, presents some other options.
- If it's a problem you can recover from, i.e. you can continue the application even though the
searchView
isn't there, just do so. For example, just return from the method. It's a good idea to log this situation though, so you can spot it while testing. - Otherwise, if continuing isn't possible, throw an exception. You want to fail early, so that the problem can be easily detected. A reasonable exception for this case would be IllegalStateException (see Java equivalent to .NET System.InvalidOperationException). It basically indicates that this method was executed at an inappropriate time. Be careful though, that as a
RuntimeException
, these exceptions are unchecked, and hence will probably cause the app to crash.
Solution 2
I started to use
@SuppressWarnings("ConstantConditions")
on simple methods where I'm sure that the id is not null.
Solution 3
What @Herrbert74 suggested it surely working fine, but sometimes it's better to not add a @SuppressWarnings("ConstantConditions")
to an entire method (if it's not trivial), a better approach could be to use //noinspection ConstantConditions
on the warned line.
Those are my rules of thumb:
Use
@SuppressWarnings("ConstantConditions")
when the method is simpleUse
//noinspection ConstantConditions
when the method is complex and you need to remove the warning only on a specific line
Solution 4
I personally prefer using try{ }catch{ } simply because it is more elegant. However, it does add a lot of bulk to your code, if you imagine putting every, possible, NULL value into a try catch (if they are not next to each other)
Solution 5
I like the answer to this link.
Warning is not an Error. And the warning which you are talking about says "it may produce", don't say 'it must produce'. So choice is yours. Either add null check or not
So, If you are sure that findViewById in your code will never be cause of NPE, then don't add the null check.
Hackmodford
By day, I work for DornerWorks as a Mobile Applications Dev... you get the idea. By night, I am the creator of Undulib, the audiobook player for audio drama enthusiast. I also developed the BigFinish App for Big Finish Productions.
Updated on March 23, 2020Comments
-
Hackmodford about 4 years
I'm new to android/java programming and am confused how to properly deal with this warning.
Method invocation '' may produce 'Java.lang.NullPointerException'
Should I be ussing assert to remove the warning?
Or rather a runtime exception?
Any help would be appreciated.
-
Thorn G almost 10 yearsYour own linked answer states it is possible to enable assert keyword on a real device (though obviously only via ADB).
-
matiash almost 10 years@TomG AFAIK setprop can only be used on rooted devices. But maybe I'm wrong?
-
Thorn G almost 10 yearsOoh, you may be right -- I've only used it on rooted kiosk style devices myself. Nevermind!
-
SMBiggs about 8 yearsThe vast majority of these warnings come just after findViewById() calls, which can happen a LOT! As android programmers we are used to the null-pointer errors that come from these and use them to debug when making changes to layout files. Having to test Every Single One of these calls is a super pain-in-the-ass. This new "feature" (old versions of Android Studio don't have this warning) greatly increases code bloat.
-
Iwo Banas almost 8 years@ScottBiggs luckily you can now disable the warning for certain methods. See my answer below.
-
Adrien Dos Reis almost 8 yearsPerfect, that's what we want. Disable the check only on methods where we are sure that the id cannot be null.
-
andreikashin over 5 yearsVery elegant solution. +1
-
SMBiggs over 4 yearsOr use this in places where you WANT the null-pointer errors (like in
onCreate
). -
Chaitanya Karmarkar over 3 yearsMy personal opinion //noinspection ConstantConditions is better.