Method invocation may produce NullPointerException Retrofit Body
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.
}
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..
Just use this null
pointer check.
If(response != null && response.isSuccessfull())
{
// body
}