【问题标题】:How to fix the IndexOutOfBoundsException in RecyclerView如何修复 RecyclerView 中的 IndexOutOfBoundsException
【发布时间】:2018-06-17 14:09:51
【问题描述】:

我的应用程序中有一堆 RecyclerViews,并且在 Fabric 中看到这个异常已经有一段时间了。

堆栈跟踪:

Fatal Exception: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 8(offset:8).state:11 android.support.v7.widget.RecyclerView{3914473e VFED.... ........ 0,0-1080,1509 #7f11017a app:id/chatlist_recycler_view}, adapter:com.myapp.application.a.c@134b699f, layout:android.support.v7.widget.LinearLayoutManager@1449aec, context:com.myapp.application.activities.HomeActivity@1fcf5f5e
   at android.support.v7.widget.RecyclerView$Recycler.clear(Unknown Source)
   at android.support.v7.widget.GapWorker.add(Unknown Source)
   at android.support.v7.widget.GapWorker.add(Unknown Source)
   at android.support.v7.widget.GapWorker.remove(Unknown Source)
   at android.support.v7.widget.GapWorker.add(Unknown Source)
   at android.support.v7.widget.GapWorker.run(Unknown Source)
   at android.os.Handler.handleCallback(Handler.java:739)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:5951)
   at java.lang.reflect.Method.invoke(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

查看这个更新后的堆栈跟踪,我的chatlist_recycler_view 似乎有问题。

我应该如何调试和修复它?我不知道是什么导致了 IndexOutOfBoundsException。

RecyclerView 声明中的代码:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

  <android.support.v7.widget.RecyclerView
  android:id="@+id/chatlist_recycler_view"
  android:background="@android:color/white"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:isScrollContainer="false"/>

</RelativeLayout>

如果你们需要任何其他代码,请告诉我!

适配器代码可以在这里找到:

https://pastebin.com/HzMkCDh5

【问题讨论】:

标签: android android-recyclerview indexoutofboundsexception


【解决方案1】:

嗯,IndexOutOfBoundsException 异常是一种常见的异常,但对于 recyclerview,您可以更改它以避免异常。

1:当您分配布局适配器时,只需禁用预测动画

   mRecyclerView.setLayoutManager(new LinearLayoutManager(this){
     @Override
    public boolean supportsPredictiveItemAnimations() {
        return false;
    }
});

2:如果数据集较大,可以尝试清空现有的回收池,然后通知数据变化。

mRecyclerView.getRecycledViewPool().clear();
mAdapter.notifyDataSetChanged();

3:不要使用notifyItem.....(),只使用notifyDataSetChanged()

4:如果稍后从 API 获取数据,您可以尝试再次交换适配器

swapAdapter(adapter, true)

5:确保你没有在启动时将recyclerview滚动到某个位置,如果数据不一致,这也可能导致与索引相关的问题。

链接:source

【讨论】:

  • 我不确定我知道如何触发这个异常。我会采纳你的建议
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
相关资源
最近更新 更多