Retrofit Android: Method invocation 'getSuccess' may produce 'java.lang.NullPointerException'

一笑奈何 提交于 2019-12-24 19:18:34

问题


I am using Retroft and GSON for parsing the response.

My onResponse code is like below

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

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

How to avoid this warning?

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


回答1:


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)

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) {
    ...
}


来源:https://stackoverflow.com/questions/46068141/retrofit-android-method-invocation-getsuccess-may-produce-java-lang-nullpoin

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