Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete child from firebase [duplicate]

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" ?

like image 914
Sreekanth Karumanaghat Avatar asked Sep 27 '17 12:09

Sreekanth Karumanaghat


2 Answers

ref.child("mockChild").removeValue();

Code to add child - ref.child("mockChild").push().setValue("Hello");

Added child

Code to remove child - ref.child("mockChild").removeValue();

Removed image

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.

like image 98
Martin Lund Avatar answered Oct 19 '22 15:10

Martin Lund


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.

like image 25
Alex Mamo Avatar answered Oct 19 '22 17:10

Alex Mamo