改造 Android:方法调用“getSuccess"可能会产生“java.lang.NullPointerException"

编程入门 行业动态 更新时间:2024-10-22 19:32:30
本文介绍了改造 Android:方法调用“getSuccess"可能会产生“java.lang.NullPointerException"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用 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"

本文发布于:2023-10-31 07:31:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545440.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可能会   方法   getSuccess   Android   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!