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);
}
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.