Firebase - Child inside another Child

Asked

Viewed 601 times

0

I wonder how I can put a Child inside another Child in the firebase, for example, create a Child that calls "Company" and inside that Child put other Childs with each headquarters inside, I do not know if I was clear, please help me. PS: I’m using android studio. Thank you in advance.

2 answers

1

You can use ref.child() on a nonexistent Child and give a ref.push() to create. So just do it:

DatabaseReference empresaRef = ref.child("Empresa");

To access the headquarters:

DatabaseReference sedeRef = empresaRef.child("Sede");

And to create a new one is just:

Empresa empresa = new Empresa();
Sede sede = new Sede();
DatabaseReference empresaRef = 
ref.child("Empresa").push().setValue(empresa);
DatabaseReference sedeRef = empresaRef.child("Sede").push().setValue(sede);

However, it is recommended that you save yourself using a unique ID instead of the name. To generate the ID use:

Empresa empresa = new Empresa();
Sede sede = new Sede();

String empresaID = ref.push().getKey();
DatabaseReference empresaRef = ref.child(empresaID);
empresaRef.setValue(empresa);

String sedeID = empresaRef.push().getKey();
DatabaseReference sedeRef = empresaRef.child(sedeID);
sedeRef.setValue(sede);

;)

0

First you have to set the values you need, starting with your root, after root you go through the parent node and the parent you raise your desired child.

Example:

Firebase newRef = ref.child("root").child("empresa").child("sede").push();
newRef.setValue("DollOnWorld");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.