改造方法调用可能会产生“java.lang.NullPointerException" [英] Retrofit Method invocation may produce 'java.lang.NullPointerException'

查看:75
本文介绍了改造方法调用可能会产生“java.lang.NullPointerException"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Retrofit 2.3.0 我在 Android Studio 中收到以下消息

有关如何删除此 IDE 错误消息的任何建议.谢谢

解决方案

来自 回复文档:

<块引用>

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

这篇关于改造方法调用可能会产生“java.lang.NullPointerException"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆