Han Laoper Han Laoper - 2 months ago 16
Android Question

Trying to delete specific nodes from database?

see database screenshot here

The code below does not remove all 'adam' values from the database. Why?

DatabaseReference users = FirebaseDatabase.getInstance().getReferenceFromUrl("https://newproj-54f76.firebaseio.com/users");

Query queryRef = users.equalTo("adam");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
System.out.println("remove all adam"); //doesn't happen
appleSnapshot.getRef().removeValue();
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
}
});


I will accept the correct answer.

Answer Source

Try using this code:

DatabaseReference users = FirebaseDatabase.getInstance().getReferenceFromUrl("https://newproj-54f76.firebaseio.com/users");                                    

users.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
            if(String.valueOf(appleSnapshot.getValue().equals("adam"))){
                //you can use .contains instead of .equals if you want partial match
                System.out.println("remove all adam"); //doesn't happen
                appleSnapshot.getRef().removeValue();
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});