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
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With