在RecyclerView中并发修改

时间:2018-08-31 09:35:18

标签: android android-recyclerview recycler-adapter

List中的RecyclerView删除项目时遇到问题。它包含已检查项目的列表。我要取消选中列表中的一项。

因此,方法removeGroupItem()从已检查项目列表中删除项目。在这里:

private void removeGroupItem(String groupId) {
    for (String group : pickedGroups) {
        if (group.equals(groupId))
            pickedGroups.remove(group);
    }
}

如果我在某个项目上快速点击2-3次,则会崩溃。 这是stacktrace:

java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.next(ArrayList.java:860)
        at com.camness.vidimguploadjun2016.trips.group_adapter.GroupsAdapter.removeGroupItem(GroupsAdapter.java:76)
        at com.camness.vidimguploadjun2016.trips.group_adapter.GroupsAdapter.access$300(GroupsAdapter.java:16)
        at com.camness.vidimguploadjun2016.trips.group_adapter.GroupsAdapter$GroupViewHolder.lambda$new$0$GroupsAdapter$GroupViewHolder(GroupsAdapter.java:65)
        at com.camness.vidimguploadjun2016.trips.group_adapter.GroupsAdapter$GroupViewHolder$$Lambda$0.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:6303)
        at android.widget.CompoundButton.performClick(CompoundButton.java:134)
        at android.view.View$PerformClick.run(View.java:24828)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6798)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

在此先感谢大家的帮助。

1 个答案:

答案 0 :(得分:0)

首先改变工作逻辑。例如,删除后可以中断

    synchronized(pickedGroups) {
       for (String group : pickedGroups) {
           if (group.equals(groupId)) {
               pickedGroups.remove(group);
               break;
           }
       }
    }

但是您还必须同步有权访问该数组的线程。例如

<form action="www.foo.com/">
<input type="text" value="0" name="test"/>
<input type="text" value="" name="promo_code"/>
</form>