Skip to content Skip to sidebar Skip to footer

Retrofit Method Invocation May Produce 'java.lang.nullpointerexception'

Using Retrofit 2.3.0 I am getting the following message in Android Studio Any suggestions on how I could remove this IDE error message. Thanks

Solution 1:

From the Response documentation:

@Nullablepublic 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:

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

Post a Comment for "Retrofit Method Invocation May Produce 'java.lang.nullpointerexception'"