Bippan Kumar
Bippan Kumar

Reputation: 718

Firebase Realtime Database delete item in List

I have the data stored in the Realtime Database in this format:

enter image description here

If I wanted to delete one of the entries in the list named 7P3MRvkC2FQkwcyC7CYVWZP9Ps72, I use this code. The id under this is generated automatically:

FirebaseDatabase.getInstance()
                .getReference()
                .child("users")
                .child(id) -------------------> unique id
                .orderByChild("orderId")
                .equalTo(orderId,"orderId")
                .getRef()
                .removeValue();

But this deletes the complete list of users.

Upvotes: 0

Views: 466

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

But this deletes the complete list of users.

That's the expected behavior. If you need to remove only the elements where the orderId property holds the value of a particular "orderId", then you should iterate trough the results like in the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
DatabaseReference uidRef = usersRef.child(uid);
Query query = uidRef.orderByChild("orderId").equalTo(orderId);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            ds.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

Upvotes: 0

Wowo Ot
Wowo Ot

Reputation: 1529

Try this code

DatabaseReference ref = FirebaseDatabase.getInstance()
            .getReference()
            .child("users")
            .child(id);

ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    dataSnapshot.getRef().removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            // notify
                        }
                    });
                }

Upvotes: 1

Related Questions