KimiTom
KimiTom

Reputation: 37

How can I remove specific item from List when data in firebase realtime db is removed?

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);
        }

Upvotes: 0

Views: 90

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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);

Upvotes: 1

Related Questions