Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Insert new data in existing array in Firebase Database from Android?

I'm Learning the Firebase Database with Android, Having array of data in Firebase Database Like Below image.

enter image description here

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.

like image 516
Yugesh Avatar asked Jun 22 '17 07:06

Yugesh


People also ask

Which method used to update the Firebase data in Android?

Which method used to update the Firebase data? Explanation: We can update the Firebase data using update command.


1 Answers

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"
like image 189
Alex Mamo Avatar answered Sep 16 '22 18:09

Alex Mamo