问题
I have a firebase data structure which looks like this:
|---employees
|----KJSXd4ScEmJ6N4UFc5k
|---employeeName:"semah"
|---employeeAge:"24"
|----KJW3HRh5kxm_FgU9nNV
|---employeeName:"Alex"
|---employeeAge:"35"
Now I want to delete the node -KJSXd4ScEmJ6N4UFc5k. But I only know the "employeeName": semah. I tried to delete the node with:
mFirebaseDatabaseReference
.child("employees")
.child("employeeName")
.child("semah")
.getParent()
.setValue(null);
but this won't work because "Invalid Firebase Database path: $member. Firebase Database paths must not contain '.', '#', '$', '[', or ']'"
So my question is, how can I delete the node: "-KJSXd4ScEmJ6N4UFc5k" only knowing: "semah" or how to remove element by the generated id "-KJSXd4ScEmJ6N4UFc5k".
Thanks in advance.
回答1:
Since you don't have the reference to the key KJSXd4ScEmJ6N4UFc5k, you need to retrieve the value and try deleting it with the ref of value retrieved. Something like this
database.getReference("employees").orderByChild("employeeName").equalTo("semah").addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TodoApp", "getUser:onCancelled", databaseError.toException());
}
});
回答2:
In your case you can build a query to retrieve the item to delete.
Something like:
Firebase refEmployees = new Firebase("..../employees");
Query queryRef = refEmployees.orderByChild("name").equalTo("semah");
queryRef..addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String key=snapshot.getKey();
//Remove the item
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
来源:https://stackoverflow.com/questions/37644654/delete-element-in-firebase-with-android