繁体   English   中英

在onPostExecute()中的ArrayList模型上进行For循环

[英]For loop on ArrayList Model inside onPostExecute()

onPostExecute()期间过滤/检查 ArrayList中的模型项时onPostExecute() ,我遇到异常ConcurrentModificationException,试图通过"Items"进行访问/循环

我有一个具有以下inits和onCreateView() init的活动;

//model init
List<TrackingModel> Items;


//onCreateView() {}
Items = new ArrayList<>();

//and prompt async task
new RetrieveFeedTask().execute();

在我通过URL提取JSON并在JSON数据节点上执行了循环之后,在onPostExecute()中的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);

错误发生在这里,因为我们在for循环中添加到ArrayList时无法执行.add()。

当您在列表中循环并尝试在同一循环中修改(删除/添加)时,会发生ConcurrentModificationException 这是不允许的。

相反,您可以创建另一个List并继续向其中添加元素。

我当前的解决方案是将一个temp变量(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++)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM