Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method invocation may produce NullPointerException Retrofit Body

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.

like image 799
Priya Avatar asked Oct 02 '17 04:10

Priya


People also ask

How do I fix method invocation may produce NullPointerException?

Method invocation may produce NullPointerException warning while it's checked before. What steps will reproduce the problem? Try to add toString to a variable that has been checked for null before, to reproduce the issue this checking has to be in a private method, like in the screenshot.

How do you handle null pointer exception in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.


1 Answers

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.
}
like image 75
Nabin Bhandari Avatar answered Oct 12 '22 04:10

Nabin Bhandari