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

让人想犯罪 __ 提交于 2019-12-12 12:17:37

问题


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


回答1:


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());
}


来源:https://stackoverflow.com/questions/45422911/retrofit-method-invocation-may-produce-java-lang-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!