I wish to delete specific user with phone number X from my DB. And insted my code deletes all of them.
Here is my DB:
Code:
private static void deleteUser(final Context context, final String phoneNumber) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
Query usersQuery = databaseReference.orderByChild("phone").equalTo(phoneNumber);
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Log.d(TAG, "Deleted");
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
}
Maybe it is not clear with my comment, so I am putting this as an answer, the full code that should not be having the problem you're facing, should look something like this:
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Log.d(TAG, "Deleted");
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled", databaseError.toException());
}
});
That's because you're using a singleValueEventListener
. If the query matches multiple children, it returns a list of all those children.
Even if there's only a single matches child, it's still a list of one. And since you're calling getRef()
on that list, you get the key of the location where you ran the query.
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.