Jack Jack - 1 year ago 75
Android Question

Remvoing object from a list while iterating it doesn't work (with iterator)

This is the method:

public void deleteEvent(View view){
Intent intent = new Intent(this, MainActivity.class);

for (User myUser:LocalDataBase.getEventByID(eventID).getInvitedUsersTotal()){
for (Event myEvent:myUser.getAttendingList())
ListIterator<Event> itr_attending =myUser.getAttendingList().listIterator();
if (myEvent.getId()==eventID){


Toast.makeText(getApplicationContext(), "The event was deleted",Toast.LENGTH_LONG).show();

This method is in order to delete an event from the database. In order to do it I need to remove it from the "attending list" of each invited user. (If the user says he is going to the event, the event moving to this list of him).

Each event has a list of invited users
, and for each user, the method should go over the user's attending list and serach for the wanted event
, and than delete it.

In the end, the event is not deleted from the attending list.

What am I doing wrong here?

Answer Source

Read the Javadoc of ListIterator.remove():

Removes from the list the last element that was returned by next() or previous()

You're never calling next() or previous() on the list iterator, so there's nothing to remove.

It's not very clear what you are intending to remove from the list - but the fact that you have two iterators concurrently on the same list suggests that - if you really did remove anything - you'd get a ConcurrentModificationException anyway.

I think that you need to replace the inner enhanced for loop with an explicit iteration: you can't remove from a list that you're iterating with an enhanced for loop:

for (User myUser: ...){
  Iterator<Event> it = myUser.getAttendingList().iterator();
  while (it.hasNext()) {
    Event myEvent = it.next();
    if (myEvent.getId()==eventID){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download