Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to handle Android Studio's NullPointerException lint warning

I'm new to android/java programming and am confused how to properly deal with this warning.

Method invocation '' may produce 'Java.lang.NullPointerException'

enter image description here

Should I be ussing assert to remove the warning? enter image description here

Or rather a runtime exception? enter image description here

Any help would be appreciated.

like image 517
Hackmodford Avatar asked Apr 29 '14 17:04

Hackmodford


1 Answers

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 overriding onOptionsItemSelected(), 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.
like image 131
matiash Avatar answered Sep 20 '22 20:09

matiash