【问题标题】:ConcurrentModificationException with mutable list from Observer来自观察者的可变列表的 ConcurrentModificationException
【发布时间】:2020-07-09 06:34:50
【问题描述】:

问候,有人可以帮我解决这个问题,我已经实现了一个辅助列表来添加来自观察者的元素,但问题仍然存在,ConcurrentModificationException 发生在 addAll 行上。

在 Fragment 类中,我有一个来自项目经理的观察者,该经理提供将显示在 arraylist 上的元素列表

manager.getMutableList()
            .observe(viewLifecycleOwner, Observer { mutableList ->
                val auxList = mutableListOf<CustomClass>().apply {
                    addAll(mutableList)
                }
                if (auxList.isNotEmpty()) {
                    ...
                } else {
                    ...
                }

                (recyclerView.adapter as RecyclerAdapter).run {
                    items = auxList
                    notifyDataSetChanged()
                    ...
                }
            })

这是堆栈跟踪

java.util.ArrayList$SubList.size (ArrayList.java:1057)
java.util.ArrayList.addAll (ArrayList.java:588)
com.project.project.Fragment$setObservers$6.onChanged (Fragment.java:330)
com.project.project.Fragment$setObservers$6.onChanged (Fragment.java:74)
androidx.lifecycle.LiveData.considerNotify (LiveData.java:131)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1101)

任何帮助将不胜感激!

【问题讨论】:

    标签: java android android-livedata concurrentmodification mutablelist


    【解决方案1】:

    问题是您从主线程以外的线程修改了mutableList。避免这些异常的最好方法是使您的列表不可变(所以只需使用List 而不是MutableList)。

    所有想要修改它的代码都需要制作自己的副本:

    val copy = list.toMutableList()
    copy.add(...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2017-08-13
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多