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

点击RecyclerView条目后应用崩溃,向另一RecyclerView展示数据时出错如何解决

问题排查与修复方案

1. 空指针异常(概率最高的崩溃原因)

你在onResponse回调里的代码顺序错误:

courseinfo courseinfo=response.body();
Log.i("Response",String.valueOf(courseinfo.getMessage()));

这两行写在response.isSuccessful()和response.body()!=null判断之前,如果接口请求成功但是返回体为空,或者接口返回非2xx的错误响应时,response.body()就是null,直接调用courseinfo.getMessage()就会触发空指针崩溃。
修复方式:调整代码顺序,所有对response.body()的操作都放在非空判断之后:

@Override
public void onResponse(Call<courseinfo> call, Response<courseinfo> response) {
    progresshandler.hide();
    if(response.isSuccessful() && response.body()!=null){
        courseinfo courseinfo=response.body();
        Log.i("Response",String.valueOf(courseinfo.getMessage()));
        if("success".equals(courseinfo.getStatus())){
            settel(courseinfo.getBlogs());
            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
        }
    }else{
        Toast.makeText(getApplicationContext(), "请求失败,响应为空", Toast.LENGTH_SHORT).show();
    }
}

2. RecyclerView未设置LayoutManager

RecyclerView必须绑定LayoutManager才能正常渲染,如果你没有在初始化coureseview的地方添加如下代码,就会触发崩溃:

// 初始化coureseview的时候添加,根据你的布局需求选线性、网格、瀑布流布局即可
coureseview.setLayoutManager(new LinearLayoutManager(this));

3. setText参数类型错误

如果blogs.get(position).getPoint()返回的是int、float等数字类型,直接传入setText()方法时,系统会把数字当成字符串资源id去查找,找不到对应资源就会崩溃。
修复方式:转成String类型再赋值:

holder.point.setText(String.valueOf(blogs.get(position).getPoint()));

4. 其他注意事项

你当前接口请求写死了传参id为"1",如果是点击第一个RecyclerView的条目要传对应条目的id,记得把这个固定值替换成点击事件拿到的对应id参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:54:06