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

混江龙づ霸主 提交于 2021-02-11 14:28:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!