我使用 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() != null 和 response.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"
发布评论