android - 从数组列表中删除元素后的java.util.ConcurrentModificationException android

标签 android exception arraylist java.util.concurrent

我的 android 应用中有以下代码:

/**
 * callback executed after fetching the data.
 */
public void OnPointsFetch(ArrayList<Shop> result) {

    toggleLoader(false);

    this.shops = result;

    if(activeFilter == Constants.POINTS_FILTER_AVAILABLE){
        for(Shop s : result){
            if(s.getClientPoints().getPointsAvailable() == 0){
                this.shops.remove(s);
            }
        }
    }
    else{
        for(Shop s : result){
            if(s.getClientPoints().getPointsSpent() == 0){
                this.shops.remove(s);
            }   
        }
    }


    ptsListAdapter.setCollection(this.shops);
    ptsListAdapter.setFilter(this.activeFilter);

}

在异步任务的结果上调用此方法。在传递给列表适配器之前,我需要删除集合的一些元素。

    11-23 17:39:59.760: E/AndroidRuntime(19777): java.util.ConcurrentModificationException
11-23 17:39:59.760: E/AndroidRuntime(19777):    at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)

最佳答案

您不能在迭代列表时从列表中删除项目。您需要使用迭代器及其 remove 方法:

for(Iterator<Shop> it = result.iterator(); it.hasNext();) {
    Shop s = it.next();
    if(s.getClientPoints().getPointsSpent() == 0) {
        it.remove();
    }   
}

关于android - 从数组列表中删除元素后的java.util.ConcurrentModificationException android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13533715/

相关文章:

c# - 如何创建一个Windows App(C#),在其中可以在消息框中显示各种对象中的所有异常

java - Arraylist 覆盖值问题?

android - 如何在 Jetpack Compose 中为按钮的宽度设置动画

java - 当构造函数可能抛出受检查异常时如何实现 Singleton

c# - 当我不知道它可能抛出的位置时如何记录异常?

java - 由于值被清除,无法从使用数组列表的 HashMap 中获取值

java - 对NX3矩阵进行排序(最有效的方法)

android - 更改 ImageButton 的 ImageBitmap 的动画

android - java.lang.NoSuchMethodError : No static method metafactory 错误

java - 将图像从一项 Activity 发送到另一项 Activity