RecyclerView: No adapter attached; skipping layout

开发中经常出现整个页面只需要一个RecyclerView做布局实现的情况,然后在启动APP的时候因为是异步获取数据的,在没有获取到数据时候就开始加载RcyclerView就会出现RecyclerView: No adapter attached; skipping layout致使APP无缘无故崩溃,甚至不会出现崩溃日志。

解决办法是:

在初始化布局的时候设置空的数据源,并设置RcyclerView的数据显示。在加载布局完成之后通过adapter.notifyDataSetChanged();进行刷新数据就可以避免出现RecyclerView: No adapter attached; skipping layout.

以下是部分代码:

public class TestFragment extends BaseFragmetn{
private List data;

  @Override
    protected View initView() {
        return View.inflate(getActivity(), R.layout.fragement_counselor, null);
    }

    @Override
    protected void init() {
        // 在加载完布局之后创建空的数据源,设置进RecyclerView
        data = new ArrayList<>();
        // 设置RecyclerView的布局管理器
        rvCounselor.setLayoutManager(new GridLayoutManager(MyApp.getInstance(), 2));
        // 设置每个Item的间距
        rvCounselor.addItemDecoration(new SpaceItemDecoration(DensityUtils.dp2px(MainActivity.getInstance(), 15f)));
        // 设置Adapter
        adapter = new CounselorAdapter(MyApp.getInstance(), data);
        rvCounselor.setAdapter(adapter);
        // 设置监听
        adapter.setOnItemClick(new CounselorAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                int id = data.get(pos).getId();
                Intent intent = new Intent(MyApp.getInstance(), CounselorInfoActivity.class);
                intent.putExtra(Constant.INTENT_COUNSELOR_ID, id);
                startActivity(intent);
            }
        });
    }

 @Override
    public void setData2View(Counselor counselor) {
        // 异步加载完数据之后添加进数据源中然后通知Adapter刷新数据
        data.addAll(counselor.getData());
        adapter.notifyDataSetChanged();
    }

}

END

你可能感兴趣的:(RecyclerView: No adapter attached; skipping layout)