0

I have an issue when filtering/checking my model items in ArrayList during onPostExecute() which I get an exception ConcurrentModificationException trying to access/loop through "Items"

I have an activity that has the below inits and onCreateView() inits;

//model init
List<TrackingModel> Items;


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

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

This exception occurs during the Items loop inside onPostExecute() after I have fetched JSON via URL and done a loop on the JSON data nodes.

//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);

        }
     }
  }
}

Do I need to add to the array inside the "Items" for-loop via method?

outsideMethodAddToItems(id, another_string, more_string);

Abraham
  • 8,525
  • 5
  • 47
  • 53
BENN1TH
  • 2,003
  • 2
  • 31
  • 42
  • Try using `Iterator` and here is an example https://stackoverflow.com/questions/18448671/how-to-avoid-concurrentmodificationexception-while-removing-elements-from-arr – Sivakumar S Jan 28 '18 at 06:55

2 Answers2

0

error occurs here as we are adding to ArrayList cant do .add() when in for loop ....

ConcurrentModificationException occurs when your loop through the list and try modify (remove/add) it in the same loop. This is not allowed.

Rather, you could create another List and keep adding your elements to it.

Ravi
  • 30,829
  • 42
  • 119
  • 173
  • Ok i should check is duplicate/exists and set Bool then check bool after loop finished then do the add() if bool is false... – BENN1TH Jan 28 '18 at 06:40
  • @BENN1TH you are going to main `List`, then when not just have another `List< TrackingModel >` and keep adding your element it ? – Ravi Jan 28 '18 at 06:42
  • I thought just have a temp boolean within the for loop in the jsonObj and check at end if Item for loop ... no need to create another list? – BENN1TH Jan 28 '18 at 06:44
  • @BENN1TH remember it is list, you will go through multiple iterations and your boolean would be overwritten at any iteration. So how would you use simple variable instead of `List` ? Have you thought it ? – Ravi Jan 28 '18 at 06:45
  • temp boolean gets set to true (set to false by default) if item found in the For loop – BENN1TH Jan 28 '18 at 06:46
  • Just tested this and seems to work well, not sure about performance though but get the job done. – BENN1TH Jan 28 '18 at 06:49
0

I current solution is to have a temp variable(boolean) which is set to false and inside the loop if a item matches set the temp boolean to true. I then do a check to see if the temp Boolean set to true, if not I can run 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++)
BENN1TH
  • 2,003
  • 2
  • 31
  • 42