5

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.

1 Answer 1

5

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Can't insert the data i expect right. Insert data only like you suggest.
your answer is working fine. your structure is different and My structure is different. So, not possible create structure like "cineIndustry" : [ { "type" : "Hollywood" }, { "type" : "Kollywood" }, { "type" : "Bollywood" } ] this. Your answer is the only way right.
This is a proposal for changing the database. No, you cannot have different childrens with the same key, because in the case of a Map, it replaces the old value with the new one. So that why you need different keys.
Okay I'll go with your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.