Android Studio用Retrofit调用新冠API显示数据遇空指针问题求助
解决方案:NullPointerException 问题排查与修复
核心问题定位
报错java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.apicovid.Model.getDeaths()' on a null object reference,直接说明调用getDeaths()方法时,对应的Model对象为null——即API请求返回的数据未被正确解析为Model实例,或请求过程中出现异常导致Model对象未初始化。
以下分模块排查修复:
1. 修正Model类的字段映射
API返回的deaths、recovered为数字类型(long/int),若Model类将其定义为String类型,解析库会无法映射,导致Model实例为null。同时必须提供无参构造函数供解析库使用:
public class Model { private long updated; private long deaths; private long recovered; // 无参构造函数(必填) public Model() {} // Getter方法 public long getDeaths() { return deaths; } public long getRecovered() { return recovered; } public long getUpdated() { return updated; } }
2. 修正APIService接口定义
API返回单个对象而非数组,接口方法的返回类型需为Call<Model>:
public interface APIService { @GET("v2/all") Call<Model> getGlobalData(); }
3. 完善MainActivity的请求回调逻辑
必须在请求成功且返回体非空时,才调用Model的get方法,同时处理请求失败场景:
public class MainActivity extends AppCompatActivity { private TextView tvDeaths, tvRecovered; private APIService apiService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvDeaths = findViewById(R.id.tv_deaths); tvRecovered = findViewById(R.id.tv_recovered); // 初始化Retrofit与APIService Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://corona.lmao.ninja/") .addConverterFactory(GsonConverterFactory.create()) .build(); apiService = retrofit.create(APIService.class); fetchData(); } private void fetchData() { Call<Model> call = apiService.getGlobalData(); call.enqueue(new Callback<Model>() { @Override public void onResponse(Call<Model> call, Response<Model> response) { if (response.isSuccessful() && response.body() != null) { Model data = response.body(); tvDeaths.setText(String.valueOf(data.getDeaths())); tvRecovered.setText(String.valueOf(data.getRecovered())); } else { tvDeaths.setText("数据加载失败"); } } @Override public void onFailure(Call<Model> call, Throwable t) { tvDeaths.setText("请求失败:" + t.getMessage()); } }); } }
4. 核对布局文件的TextView ID
确保activity_main.xml中TextView的ID与MainActivity中findViewById的ID完全一致:
<TextView android:id="@+id/tv_deaths" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/tv_recovered" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
5. 配置网络权限与明文流量
- 在
AndroidManifest.xml添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
- 针对Android 9及以上,在application标签中启用明文流量:
<application ... android:usesCleartextTraffic="true"> ... </application>
内容的提问来源于stack exchange,提问作者StressCodingCok
相关产品推荐
相关产品推荐

