Method invocation may produce NullPointerException Retrofit Body

46,923

Solution 1

It is just a warning as it will never be null if the response is successful. You can ignore it or wrap around if(response.body() != null) to remove the warning.

Ads ads = response.body();
if(ads != null){
    constant.banner_on = ads.getBanner_on();
    // and so on.
}

Solution 2

Using if is great but there is only one line, much cleaner way is:

constant.banner_on = ads != null ? ads.getBanner_on() : null;

If you are using Java 8, you can do a assertion before assignment:

Ads ads = response.body();
assert ads != null;
constant.banner_on = ads.getBanner_on();

Another way to do this is using Objects.requireNonNull() before assignment:

constant.banner_on = Objects.requireNonNull(ads.getBanner_on());

That is actually designed primarily for param validation. Source code comment:

/**
     * Checks that the specified object reference is not {@code null}. This
     * method is designed primarily for doing parameter validation in methods
     * and constructors, as demonstrated below:
     * <blockquote><pre>
     * public Foo(Bar bar) {
     *     this.bar = Objects.requireNonNull(bar);
     * }
     * </pre></blockquote>
     * 

One great SO answer about this is here. Also read this to get understanding why we need to explicitly check..

Solution 3

Just use this null pointer check.

If(response != null && response.isSuccessfull())
{

// body

}
Share:
46,923
Priya
Author by

Priya

Updated on July 09, 2022

Comments

  • Priya
    Priya almost 2 years

    I am using Retrofit 2 for get response from my API and store its value in my constant like below

    if(response.isSuccessful()) {
                        constant.banner_on = response.body().getBanner_on();
                        constant.int_on = response.body().getInt_on();
                        constant.int_click = response.body().getInt_click();
                    }
    

    It's giving me warning on all three like below

    Method invocation getBanner_on may produce java.lang.nullPointerException

    I am confused and unable to resolve this warning. Let me know if someone can help me to come out from this.

  • emilpmp
    emilpmp over 6 years
    @priya i am not sure about this, but can you check null pointer for response.getBody() as well? That is if (response !=null && respone.getBody() ! =Null) { ... }