Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress potential NullPointerException in Android Studio

This:

@Nullable Item[] mItems;  public Item getItem(int position) {     return mItems[position]; } 

produces the warning:

Array access 'mItems[position]' may produce NullPointerException 

I want to suppress this warning (I know that getItem() will not be called if mItems is null).

I've tried using the following annotations:

  • @SuppressWarnings({"NullableProblems"})
  • @SuppressWarnings({"null"})

as well as with the //noinspection notation, but they're all not working.

Using @SuppressWarnings({"all"}) works, but it's obviously not what I'm looking for.

Android Studio doesn't offer any suppression option when I hit alt + enter, just the options to add a (useless) null check.

like image 655
minipif Avatar asked Aug 11 '15 01:08

minipif


People also ask

How do I fix null pointer exception in Android?

How to fix the NullPointerException? To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app.

How to suppress null pointer exception in java?

Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.

What is NullPointerException in Android Studio?

java.lang.NullPointerException. Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.


2 Answers

This works for me, but not sure why AS would want to use constant conditions as the suppressor. I think it has something to do with the skip null check as it's a constant condition (i.e., it'll always not be null).

@Nullable Item[] mItems;  @SuppressWarnings("ConstantConditions") public Item getItem(int position) {     return mItems[position]; } 
like image 86
zerobasedindex Avatar answered Oct 03 '22 22:10

zerobasedindex


If you want to prevent Android Studio from bothering you with those warnings while keeping them in the compiler simply go to Settings -> Editor -> Inspections -> Constant Conditions and Exceptions and uncheck it.

If instead you want to completely remove it then use the proper SuppressWarnings as suggested by the other answers :

@SuppressWarnings("ConstantConditions") 
like image 30
sam Avatar answered Oct 03 '22 23:10

sam