0

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);
        }
KimiTom
  • 37
  • 2
  • 5

1 Answers1

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);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you very much! This is what I wanted to know. In my code, I initialized 'todoItemKeys' as below and tried the solution. It works~ `final List todoItemsKeys = new ArrayList<>();` – KimiTom Dec 17 '18 at 15:49