1

I've got a problem with removing items from List in RecyclerView. It contains list of checked items. I want to uncheck one item of the list.

So, method removeGroupItem() removes item from list of checked items. Here it is:

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

If I tap very fast 2-3 times on some item - it crashes. Here is 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)

Thank you all in advance for any help.

Nazarii Moshenskiy
  • 1,802
  • 2
  • 16
  • 35

1 Answers1

1

First of all change the logic of work. For example you can break after remove

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

But you also have to synchronize the threads which have access to this array. For example

    synchronized(pickedGroups) {
       for (String group : pickedGroups) {
           if (group.equals(groupId)) {
               pickedGroups.remove(group);
               break;
           }
       }
    }
Eugene Babich
  • 1,271
  • 15
  • 25
  • if you break it, the for loop won't work after because you exit it. which means, only first one gets removed. – c-an Apr 18 '20 at 13:47