问题
When a data in realtime database is removed, I want to remove the data from list as well. I wrote following code, but it does not work. Is there anybody can help me?
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
TodoItem todoItem = dataSnapshot.getValue(TodoItem.class);
todoItems.add(todoItem);
adapter.setTodoItems(todoItems);
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
TodoItem todoItem = dataSnapshot.getValue(TodoItem.class);
todoItems.remove(todoItem);
adapter.setTodoItems(todoItems);
}
回答1:
You will need to keep the keys of the TODO items from the database in onChildAdded
. Then when onChildRemoved
gets called, you can look up the position of the item by its key and remove it from the todoItems
list based on its position.
So in onChildAdded
:
todoItems.add(todoItem);
todoItemKeys.add(dataSnapshot.getKey());
And then in onChildRemoved
:
int index = todoItemKeys.indexOf(dataSnapshot.getKey());
todoItems.remove(index);
todoItemKeys.remove(index);
来源:https://stackoverflow.com/questions/53803670/how-can-i-remove-specific-item-from-list-when-data-in-firebase-realtime-db-is-re