在ArrayList
期间onPostExecute()
中过滤/检查我的模型项时出现问题我遇到异常 ConcurrentModificationException 尝试通过"Items"
我的活动具有以下内容和onCreateView()
次;
//model init
List<TrackingModel> Items;
//onCreateView() {}
Items = new ArrayList<>();
//and prompt async task
new RetrieveFeedTask().execute();
在我通过onPostExecute()
提取JSON
并在URL
数据节点上完成循环后,在JSON
内的Items循环期间发生此异常。
//For Loop on JSON Response in onPostExecute()
JSONArray data = obj.getJSONArray("response");
for (int i = 0; i < data.length(); i++) {
String id = data.getJSONObject(i).optString("id");
//in here I add to Items, first checking if Items.isEmpty()
if(Items.isEmpty()){
//add to Model/Items.ArrayList
//works fine
TrackingModel reg = new TrackingModel();
reg.setId(id);
Items.add(reg);
}else{
//check getJSONObject() item already in Items.ArrayList to avoid duplications
for (TrackingModel Item : Items) {
if(Item.id().toString().contains(id)){
//already in ArrayList, skip adding
}else{
//error occurs here as we are adding to ArrayList
//cant do .add() when in for loop ....
//Do I add to the array outside the For Loop via method?
//outsideMethodAddToItems(id, another_string, more_string);
TrackingModel reg = new TrackingModel();
reg.setId(id);
Items.add(reg);
}
}
}
}
我是否需要通过方法添加到"Items"
for循环中的数组?
outsideMethodAddToItems(id, another_string, more_string);
答案 0 :(得分:0)
这里发生当您循环遍历列表并尝试在同一循环中修改(删除/添加)它时,会出现错误,因为我们在添加到ArrayList时不能执行.add() for loop ....
ConcurrentModificationException
。这是不允许的。
相反,您可以创建另一个List
并继续添加元素。
答案 1 :(得分:0)
我当前的解决方案是将临时变量(boolean)设置为false,如果项匹配则在循环内部将temp boolean设置为true。然后我检查一下temp布尔值是否设置为true,如果不是,我可以运行add();
//while inside
JSONArray data = obj.getJSONArray("response");
for (int i = 0; i < data.length(); i++) {
//temp boolean
Boolean isFound = false;
for (TrackingModel Item : Items) {
if(Item.id().toString().contains(id)){
//already in ArrayList, skip adding
//set temp boolean as true as we found a match
isFound = true;
}
}
//now we check temp boolean isFound is false, so we can run add();
if(!isFound ){
TrackingModel reg = new TrackingModel();
reg.setId(id);
Items.add(reg);
}
}
//end of for (int i = 0; i < data.length(); i++)