delete element in firebase with android [duplicate]

你。 提交于 2020-01-07 09:21:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!