Retrofit Android: Method invocation 'getSucces

2019-08-22 18:39发布

问题:

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