Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit Method invocation may produce 'java.lang.NullPointerException'

Using Retrofit 2.3.0 I am getting the following message in Android Studio

enter image description here

Any suggestions on how I could remove this IDE error message. Thanks

like image 696
Shifatul Avatar asked Dec 14 '22 21:12

Shifatul


1 Answers

From the Response documentation:

@Nullable
public T body()

The deserialized response body of a successful response.

This means that response.body() can return null, and as a result, invoking response.body().getItems() can throw a NullPointerException. To avoid the warning message, check that response.body() != null before invoking methods on it.

Edit

Discussion on another question revealed that my statements above are not as clear as they need to be. If the original code was:

mAdapter.addItems(response.body().getItems());

It will not be solved by wrapping in a null check like this:

if (response.body() != null) {
    mAdapter.addItems(response.body().getItems());
}

The linter (the thing generating the warning) has no way of knowing that each response.body() invocation is going to return the same value, so the second one will still be flagged. Use a local variable to solve this:

MyClass body = response.body();
if (body != null) {
    mAdapter.addItems(body.getItems());
}
like image 57
Ben P. Avatar answered Feb 23 '23 01:02

Ben P.