1

So I am getting a "java.util.ConcurrentModificationException at java.util.ArrayList$Itr.next(ArrayList.java:860)" error.

I know the reason I am getting this error is because I am iterating over a list at the same time that I am adding objects to that list. However, I do not know how to add a listIterator to fix this problem.

If someone could show me how to add the iterator, that would be amazing. Thank you!

I have indicated where the error starts in my code

//method to evaluate who you have chatted with and display on screen
private void readChats() {
    users = new ArrayList<>();

    reference = FirebaseDatabase.getInstance().getReference("USERS");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            users.clear();


            //gets every user snapshot from "USERS" children in firebase and make User obj
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                User user = snapshot.getValue(User.class);

                //for every ID that was stored in textTransacRec list
                for (String ID : textTransacRec) {
                    //out of all existing users in firebase if a user's ID matches any of the ID's in textTransacRec
                    if(user.getID().equals(ID)) {
                        //if there are any User objects inside users list
                        if(users.size() != 0) {
                            //check to see if the user already exists in list or not by matching w/ existing user ID's
                            //if there is no ID match then user does not exist --> add to users list to display
                            //---------------------------ERROR STARTS FROM HERE----------------------
                            for(User u : users) {
                                if(!user.getID().equals(u.getID())) {
                                    users.add(user);
                                }
                            }
                        }
                        //if no User objects inside users list --> add to users list
                        else {
                            users.add(user);
                        }
                    }
                }
            }
            chatRecyclerAdap = new ChatRecyclerAdap(getContext(), users);
            recyclerView.setAdapter(chatRecyclerAdap);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
Ryan M
  • 18,333
  • 31
  • 67
  • 74
adey1
  • 31
  • 7
  • Does this answer your question? [Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Johannes Kuhn May 20 '20 at 23:42
  • I have tried looking at a few of the solutions on stackoverflow and have implemented many of them. However, I still could not get it to iterate properly. Thanks for the suggestion tho – adey1 May 21 '20 at 00:02
  • Would it be possible to write down in pseudocode what my code should look like right after my error comment? Just from the for statement to the end of the else statement – adey1 May 21 '20 at 00:03

1 Answers1

2

ListIterator has the add method, you can use it like this:

ListIterator<User> iterator = users.listIterator();
while(iterator.hasNext()) {
    User u = iterator.next();
    if(!user.getID().equals(u.getID())) {
        iterator.add(user);
    }
}

But to add a user only if it doesn't exist in the list you don't need an iterator. If you do it inside of the loop, you will add a user for each of the list's users that doesn't have the same id. But instead you need to check that the user's id is dirrenet from all users' ids and add the user only once. If you are using Java 8, you could do something like this:

    boolean userExists = users.stream().filter(u -> u.getID().equals(user.getID())).findFirst().isPresent();
    if (!userExists) {
        users.add(user);
    }
  • Thank u for the response. I have used the first code snippet u posted and the ConcurrentModification Error went away. However, now I am getting duplicate objects in my list. I don't know why this is happening. I have attached the screenshot of the app after implementing your code snippet, to show u what I mean – adey1 May 21 '20 at 02:19
  • I explained why this is happening in my answer.With the first snippet you add a user for each of the list's users that doesn't have the same id.Instead you need to check that the user's id is dirrenet from all users' ids and add the user only once. To do this you can use the second snippet. – Vladimir Zakharov May 21 '20 at 02:31
  • @adey1, does my comment answer your question? – Vladimir Zakharov May 21 '20 at 02:41