Method invocation may produce NullPointerException Retrofit Body

微笑、不失礼 提交于 2020-02-03 03:59:05

问题


I am using Retrofit 2 for get response from my API and store its value in my constant like below

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

its giving me warning on all three like below

Method invocation getBanner_on may produce java.lang.nullPointerException

I am confused and unable to resolve this warning. Let me know if someone can help me to come out from this.

Thanks


回答1:


It is just a warning as it will never be null if the response is successful. You can ignore it or wrap around if(response.body() != null) to remove the warning.

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



回答2:


Just use this null pointer check.

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

// body

}



回答3:


Its a good habit to before assigning any value from response handle null pointer exception to prevent some of exception. And you can also use try and catch to handle other exceptions.

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



回答4:


Using if is great but there is only one line, much cleaner way is:

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

If you are using Java 8, you can do a assertion before assignment:

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

Another way to do this is using Objects.requireNonNull() before assignment:

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

That is actually designed primarily for param validation. Source code comment:

/**
     * 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>
     * 

One great SO answer about this is here. Also read this to get understanding why we need to explicitly check..



来源:https://stackoverflow.com/questions/46519388/method-invocation-may-produce-nullpointerexception-retrofit-body

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