I use following code to add a child and set a value to it in FireBase.
String ref = Constants.Client+"/"+Constants.firebaseProjects+"/"+Constants.ProjectName+"/xyz";
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseRefer);
ref.child("mockChild").push().setValue("")
What can I do to delete the "mockChild" ?
ref.child("mockChild").removeValue();
Code to add child - ref.child("mockChild").push().setValue("Hello");
Code to remove child - ref.child("mockChild").removeValue();
Lets take an example in a user db:
ref.child("Users").child("User1").setvalue("User 1");
ref.child("Users").child("User2").setvalue("User 2");
ref.child("Users").child("User3").setvalue("User 3");
Now if you want to remove a specific user from the database you have to use this code:
ref.child("Users").child("User2").removeValue();
Since firebase is a key value database, it will remove the value from User2 and also the key since the key can't be on it's own. This will remove the entire reference to User2 from your database.
To solve this, please use the following code:
String key = ref.child("mockChild").push().getKey();
ref.child("mockChild").child(key).setValue("yourValue");
ref.child("mockChild").child(key).removeValue(); // This is how you remove it
or you can use:
ref.child("mockChild").child(key).setValue(null);
It's also accepted and means that when you give Firebase a null value for a property/path, you indicate that you want to property or path to be deleted.
If you want to remove the entire child, then just use:
ref.child("mockChild").removeValue();
Note, it will remove everything that mockChild
contains.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With