Android 解决java.lang.IndexOutOfBoundsException: Inconsistency detected错误 - Go语言中文社区

Android 解决java.lang.IndexOutOfBoundsException: Inconsistency detected错误


这里写图片描述

  今天测试突然找我说项目在刷新数据时偶现crash情况,经过反复测试终于重现出此错误日志,如图所示,看到此错误信息我当时也是一脸懵逼,没有报具体哪段代码的错误信息,而是报RecyclerView内部错误,于是经过google一番终于找到此错误原因,在此记录下解决方法:
  

1、创建一个继承LinearLayoutManager的类,重写onLayoutChildren方法,捕获异常,使项目不会crash掉:

public class WrapContentLinearLayoutManager extends LinearLayoutManager {
    //... constructor
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e) {
            Log.e("probe", "meet a IOOBE in RecyclerView");
        }
    }
}

2、采用notifyItemRangeRemoved + notifyItemRangeInserted方式:

int oldContentSize = itemsBeanList.size();//获取刷新前数据长度
itemsBeanList.clear();
adapter.notifyItemRangeRemoved(0,oldContentSize );
itemsBeanList.addAll(newContentList);//添加新数据
//下拉刷新时oldContentSize为0,上拉加载时为之前数据长度
adapter.notifyItemRangeInserted(oldContentSize,newContentList.size());

总结
  
  经自己测试,上面两个方法都是有效的,这个错误原因应该是adapter中数据集不一致而导致的,只需要解决外部数据集和内部数据集保持同步更新即可。有关notifyItemRangeRemoved 和notifyItemRangeInserted的含义,这里就不多说了,想了解的可以去API文档中阅读,多读读文档对自己很有帮助的。哈哈!

参考文献:https://stackoverflow.com/questions/31759171/recyclerview-and-java-lang-indexoutofboundsexception-inconsistency-detected-in

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/zl_china/article/details/77969559
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-22 11:20:41
  • 阅读 ( 602 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢