I'm Learning the Firebase Database with Android, Having array of data in Firebase Database Like Below image.
cineIndustry is an Array of data. In JSON it looks Like this
"cineIndustry" : [ {
"type" : "Hollywood"
}, {
"type" : "Kollywood"
}, {
"type" : "Bollywood"
} ]
I want Insert new data in this Array.
POJO Class
@IgnoreExtraProperties
public class CineIndustry {
void CineIndustry(){}
public String type;
}
Save new data
CineIndustry cineIndustry = new CineIndustry();
cineIndustry.type = cineType.getText().toString();
mDatabase.setValue(cineIndustry);
When i insert like above it will replace Array. JSON Structure was change to normal JSON object instated of JSON Array.
Anyone know help me to solve this issue.
Which method used to update the Firebase data? Explanation: We can update the Firebase data using update command.
This is happening because you are overwriting
the data. You are using the setValue()
method, instead of using updateChildren()
method.
Please do the following changes and your problem will be solved.
So, in order to write data objects to your Firebase database, instead of using an Array
or a List
, I suggest you using a Map
. To save data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference cineIndustryRef = rootRef.child("cineIndustry").push();
String key = cineIndustryRef.getKey();
Map<String, Object> map = new HashMap<>();
map.put(key, "Hollywood");
//and os on
cineIndustryRef.updateChildren(map);
As you can see, I have called updateChildren()
method directly on the reference. In the end, the database should look like this:
Firebase-root
|
---- cineIndustry
|
---- pushedId1: "Hollywood"
|
---- pushedId2: "Kollywood"
|
---- pushedId2: "Bollywood"
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