方法调用可能会产生NullPointerException Retrofit Body

时间:2017-10-02 04:11:09

标签: java android retrofit retrofit2

我正在使用Retrofit 2从我的API获取响应并将其值存储在我的常量中,如下所示

if(response.isSuccessful()) {
                    constant.banner_on = response.body().getBanner_on();
                    constant.int_on = response.body().getInt_on();
                    constant.int_click = response.body().getInt_click();
                }

它给了我三个警告,如下所示

Method invocation getBanner_on may produce java.lang.nullPointerException

我很困惑,无法解决此警告。如果有人可以帮助我从中脱身,请告诉我。

由于

4 个答案:

答案 0 :(得分:10)

这只是一个警告,因为如果响应成功,它将永远不会为空。您可以忽略它或环绕if(response.body() != null)以删除警告。

Ads ads = response.body();
if(ads != null){
    constant.banner_on = ads.getBanner_on();
    // and so on.
}

答案 1 :(得分:0)

只需使用此null指针检查。

If(response != null && response.isSuccessfull())
{

// body

}

答案 2 :(得分:0)

在从响应句柄null pointer exception分配任何值之前,这是一个好习惯,以防止出现异常。您还可以使用trycatch来处理其他异常。

 if(response.isSuccessful()) {
    try {
         if(response.body() != null){
                constant.banner_on = response.body().getBanner_on();
                constant.int_on = response.body().getInt_on();
                constant.int_click = response.body().getInt_click();
           }
     } catch (IOException e) {
        e.printStackTrace();
     }
   }

答案 3 :(得分:0)

使用if很棒,但是只有一行,更简洁的方法是:

constant.banner_on = ads != null ? ads.getBanner_on() : null;

如果您在分配前使用Java 8, you can do a assertion

Ads ads = response.body();
assert ads != null;
constant.banner_on = ads.getBanner_on();

另一种方法是在分配前使用 Objects.requireNonNull()

constant.banner_on = Objects.requireNonNull(ads.getBanner_on());

这实际上主要是为参数验证而设计的。源代码注释:

/**
     * Checks that the specified object reference is not {@code null}. This
     * method is designed primarily for doing parameter validation in methods
     * and constructors, as demonstrated below:
     * <blockquote><pre>
     * public Foo(Bar bar) {
     *     this.bar = Objects.requireNonNull(bar);
     * }
     * </pre></blockquote>
     * 

一个很棒的SO answer about this is here。还有read this to get understanding why we need to explicitly check.

相关问题