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

RecyclerView报错“未关联适配器”及页面崩溃问题求助

解决RecyclerView崩溃:"No adapter attached: skipping layout"问题

嘿,我来帮你搞定这个RecyclerView的崩溃问题!你看到的E/RecyclerView : No adapter attached: skipping layout错误,本质上是RecyclerView在准备渲染布局的时候,还没绑定适配器,或者适配器的数据源是null,导致它无法正常工作甚至崩溃。结合你的适配器代码,我给你一步步的解决方案:

一、先给RecyclerView绑定一个“兜底”适配器

很多新手会犯的错误是:等到异步加载完数据才给RecyclerView设置适配器,但这时候RecyclerView已经完成第一次布局了,就会触发这个错误。正确的做法是在Activity初始化RecyclerView的时候,就先绑定一个带有空数据源的适配器,之后数据加载完成再更新适配器。

比如你的Activity里应该这么写:

// 1. 初始化RecyclerView和布局管理器
RecyclerView recyclerView = findViewById(R.id.your_recycler_view_id);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

// 2. 先创建一个空的数据源列表,避免传入null
List<Categoria> categoriaList = new ArrayList<>();
// 3. 创建适配器并立即绑定给RecyclerView
RecyclerViewAdapterCategoria adapter = new RecyclerViewAdapterCategoria(this, categoriaList);
recyclerView.setAdapter(adapter);

// 4. 异步加载数据(比如从网络/数据库获取),加载完成后更新数据源并通知适配器
// 这里模拟你的数据加载逻辑
loadCategoriasFromServer(new OnDataLoadedListener() {
    @Override
    public void onDataLoaded(List<Categoria> data) {
        // 更新数据源
        categoriaList.clear();
        categoriaList.addAll(data);
        // 通知适配器数据变化,RecyclerView会重新渲染
        adapter.notifyDataSetChanged();
    }
});

二、给适配器的数据源加非空判断,避免空指针

你的适配器里直接用mData.size(),如果传入的mData是null,会直接触发空指针崩溃。我们需要在两个地方加兜底:

1. 构造方法里给mData兜底

修改适配器的构造方法,确保mData永远不会是null:

public RecyclerViewAdapterCategoria(Context mContext, List<Categoria> mData) {
    this.mContext = mContext;
    // 如果传入的mData是null,就初始化一个空的ArrayList
    this.mData = mData != null ? mData : new ArrayList<>();
    option = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);
}

2. getItemCount方法里加非空判断

修改getItemCount(),避免因为mData为null导致崩溃:

@Override
public int getItemCount() {
    // 只有mData不为null时才返回size,否则返回0
    return mData != null ? mData.size() : 0;
}

三、检查布局文件的RecyclerView配置

确保你的RecyclerView在布局文件里已经正确设置了宽度和高度(比如match_parent),不要用wrap_content(如果数据源为空的话,可能会导致布局异常)。

做完以上几步,你的RecyclerView就不会再因为“没有绑定适配器”或者空数据源而崩溃了,而且错误日志也会消失~

内容的提问来源于stack exchange,提问作者Edson Daniel Navarro Brizuela

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:26:15