You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

我的Android应用崩溃,logcat报NullPointerException空指针异常求解决

问题根因

报错指向newsModal.getArticles()调用时对象为空,本质是你直接使用了Retrofit返回的response.body(),没有做非空校验,当接口请求异常、响应解析失败时response.body()会返回null,直接调用方法就触发空指针崩溃。

修复步骤

1. 新增非空校验避免崩溃

优先修改onResponse内的逻辑,增加多重非空判断,修改后的代码如下:

call.enqueue(new Callback<NewsModel>()  {
    @Override
    public void onResponse(Call<NewsModel> call, retrofit2.Response<NewsModel> response) {
        loadingPB.setVisibility(View.GONE);
        // 先校验请求响应状态 + 响应体非空
        if (response.isSuccessful() && response.body() != null) {
            NewsModel newsModal = response.body();
            ArrayList<Articles> articlesArrayList= newsModal.getArticles();
            // 再校验返回的文章列表非空再遍历
            if (articlesArrayList != null && !articlesArrayList.isEmpty()) {
                for (int i = 0; i < articlesArrayList.size(); i++){
                    Articles item = articlesArrayList.get(i);
                    articles.add(new Articles(item.getTitle(), item.getDescription(), item.getUrlToImage(), item.getUrl(), item.getContent()));
                }
                newsRVAapter.notifyDataSetChanged();
            } else {
                Toast.makeText(MainActivity.this, "暂无新闻数据", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 打印错误信息方便排查问题
            try {
                String errorContent = response.errorBody() != null ? response.errorBody().string() : "无错误详情";
                Log.e("请求失败", "错误码:" + response.code() + ",错误内容:" + errorContent);
                Toast.makeText(MainActivity.this, "请求失败,错误码:" + response.code(), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailure(Call<NewsModel> call, Throwable t) {
        loadingPB.setVisibility(View.GONE);
        Toast.makeText(MainActivity.this, "获取数据失败:" + t.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

2. 排查响应体为空的原因

加完校验后可以根据日志排查根因:

  • 如果日志打印错误码非2xx(比如401、403、404、500),说明是接口侧问题,检查请求参数、接口密钥、请求地址是否正确
  • 如果错误码是200但body还是为空,检查NewsModel实体类字段是否和接口返回的JSON结构完全匹配,字段拼写、类型是否一致,必要时给字段加上@SerializedName注解明确映射关系
  • 检查Retrofit初始化代码,确认已经添加了Gson转换器依赖,配置了addConverterFactory(GsonConverterFactory.create())

额外注意点

不要在onResponse方法上加throws NullPointerException,空指针是运行时异常,抛出不会解决问题,必须主动做非空判断处理。

内容的提问来源于stack exchange,提问作者Zarathustra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:06:02