简体   繁体   中英

Remove object from list on child removed android

I have an arrayList of objects of a class. This class contains data received from Firebase.

but I want to remove an object from the list when a child is removed in firebase, but two objects don't match because the snapshot creates a new object of the class containing the same data. Here is the code of what I have implemented :

posts = new ArrayList<>();

        childEventListener= new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                posts.add(dataSnapshot.getValue(GalleryPostModel.class));
                unapprovedAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
                posts.remove(dataSnapshot.getValue(GalleryPostModel.class));
                unapprovedAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        };

        UnApprovedDbRef.addChildEventListener(childEventListener);

So how do I approach this problem ? what can I do to remove it from the list. I could do a linear search in the list, but when the list becomes huge, this task will become very time consuming. (Cannot use .removeIf because it requires a minimum api level 24 but my app's min api is 22)

To be able to remove the item you must keep its key, in addition to keeping the value.

So you create an addition list for the keys:

keys = new ArrayList<String>();

And then in onChildAdded , add the key of the snapshot to this list:

public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
    posts.add(dataSnapshot.getValue(GalleryPostModel.class));
    keys.add(dataSnapshot.getKey());
    unapprovedAdapter.notifyDataSetChanged();
}

Now you can look up the key in onChildRemoved , which is a lot faster than looking up the post/value:

public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
    int index = keys.indexOf(dataSnapshot.getKey());
    posts.remove(index);
    keys.remove(index);
    unapprovedAdapter.notifyDataSetChanged();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM