且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

改造方法调用可能会产生“java.lang.NullPointerException"

更新时间:2023-11-19 13:04:34

来自 回复文档:

@Nullable公共T体()

成功响应的反序列化响应主体.

这意味着 response.body() 可以返回 null,因此调用 response.body().getItems() 会抛出一个 空指针异常.为避免出现警告消息,请在调用方法之前检查 response.body() != null.

编辑

对另一个问题的讨论表明,我上面的陈述不够清晰.如果原始代码是:

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

它不会通过像这样包装一个空检查来解决:

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

linter(生成警告的东西)无法知道每个 response.body() 调用将返回相同的值,因此第二个调用仍将被标记.使用局部变量来解决这个问题:

MyClass body = response.body();如果(身体!= null){mAdapter.addItems(body.getItems());}

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.

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