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

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

问题描述

我使用 Retroft 和 GSON 来解析响应.

I am using Retroft and GSON for parsing the response.

我的onResponse 代码如下

@Override
public void onResponse(@NonNull Call<ResultList> call, @NonNull Response<ResultList> response) {
    if (response.isSuccessful()) {
        if (response.body() != null && response.body().getSuccess() == 1) {
            ................

我正在检查 response.body() != nullresponse.isSuccessful().我仍然在 Android Studio 在线 response.body().getSuccess() 中收到警告.

I am checking response.body() != null and also response.isSuccessful(). Still I am getting warning in Android studio on line response.body().getSuccess().

如何避免此警告?

我正在使用改造:2.3.0 和 gson:2.8.1.我已经尝试过这个问题的解决方案(改造方法调用可能会产生'java.lang.NullPointerException').但它不起作用

I am using retrofit:2.3.0 and gson:2.8.1. I already tried the solution on this question (Retrofit Method invocation may produce 'java.lang.NullPointerException' ). But it was not working

推荐答案

Response.body() 方法是用 @Nullable 注释声明的,这意味着它的返回值可能为空.如果要避免此警告,则必须在调用方法之前检查返回值是否为空.

The method Response.body() is declared with the @Nullable annotation, which means that its return value may be null. You must check that the returned value is not null before invoking methods if you want to avoid this warning.

您的问题包括以下代码:

Your question includes this code:

if (response.body() != null && response.body().getSuccess() == 1)

听起来您希望这会消除警告,但事实并非如此.这是因为 linter 无法知道 body() 的第二次调用将返回与第一次调用相同的值.而是这样写:

It sounds like you expect this to remove the warning, but it will not. This is because the linter has no way of knowing that the second invocation of body() will return the same value as the first invocation. Instead, write this:

ResultList body = response.body();
if (body != null && body.getSuccess() == 1) {
    ...
}

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

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