Jack Jack - 4 months ago 10
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){
itr_attending.remove();
}

}
}

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


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
(invitedUsersTotal)
, and for each user, the method should go over the user's attending list and serach for the wanted event
(myEvent.getId()==eventID)
, and than delete it.

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

What am I doing wrong here?

Answer

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){
      it.remove();
    }
  }
}