'Multiple Values Together in one child - Firebase
I am trying to save user info together in realtime firebase database, but it is not working as I expected. This is my code to save to the DB
FirebaseDatabase.getInstance().getReference().child("FYP").push().child("Name").setValue(name);
FirebaseDatabase.getInstance().getReference().child("FYP").push().child("Job").setValue(job);
FirebaseDatabase.getInstance().getReference().child("FYP").push().child("Number").setValue(number);
In return I get 3 "unique" childs that hold one piece of data. What I want is for one child to hold all 3 pieces of information. Sorry if not explained perfectly. Any help appreciated.
Solution 1:[1]
As said in the link I provided in comments "". So to ensure you only get one new unique key, you should call push() only once:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().push()
ref.child("FYP").child("Name").setValue(name);
ref.child("FYP").child("Job").setValue(job);
ref.child("FYP").child("Number").setValue(number);
Or (as a single operation:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().push()
Map<String, Object> values = new HashMap<>();
values.put("Name", name);
values.put("Job", job);
values.put("Number", number);
ref.setValue(values);
The advantage of the latter is that it's a single write operation, so writing all the properties will either succeed of fail as one.
Solution 2:[2]
For Kotlin i used a hash map,i created a child and a push so each group of values got it's own personal id:The code looks like this :
val values= hashMapOf<String,String>()
values.put("text",findViewById<EditText>(R.id.etPost).text.toString())
values.put("image",downloadUrl!!)
values.put("userUID",userUID!!)
myRef.child("post").push().setValue(values)
And this is the firebase output: -MyxdijM9aEUMbMmP59T -> unique id for each push
image: "some link" ->link of the image
text: "what's up ?" ->text
userUID: "U2z64GG7iPV2zCvhSicWpI1J" ->user id
All of them in the same child
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
| Solution 2 | Elikill58 |
