javaandroidandroid-studionullpointerexceptiongetview

NullPointerException Warning on getView() inside onActivityCreated/onStart/onViewCreated method


I know getView() might return null inside onCreateView() method, but even if I put the below code inside onActivityCreated(), onStart() or onViewCreated() methods, it still shows the warning about a possible NullPointerException in Android Studio (although my program runs without any issue). How to get rid of this warning?

I am using Fragments.

Code:

datpurchased = (EditText) getView().findViewById(R.id.datepurchased); 
//datpurchased defined as instance variable in the class

Warning:

Method invocation 'getView().findViewById(R.id.datepurchased)' may produce 'java.lang.NullPointerException'


Solution

  • Android Studio is based on IntelliJ IDEA, and this is a feature of IntelliJ that gives you warnings at compile time when you are not checking if an object returned by a method is null before using it.

    One way to avoid this is program in the style that always checks for null or catches NullPointerException, but it can get very verbose, especially for things you know will always return an object and never null.

    Another alternative is to suppress the warnings on such cases using annotations such as @SuppressWarnings for methods that use objects you know can never be null:

    @SuppressWarnings({"NullableProblems"})
    public Object myMethod(Object isNeverNull){
        return isNeverNull.classMethod();
    }
    

    or, in your case, a line-level suppression:

    //noinspection NullableProblems
    datpurchased = (EditText) getView().findViewById(R.id.datepurchased); //datpurchased defined as instance variable in the class
    

    Be sure that the objects really can never be null, though.

    More information on IntelliJ's @NotNull and @Nullable annotations can be found here, and more about inspections and supressing them here.