如何从Android在Firebase数据库的现有数组中插入新数据?

Yug*_*esh 3 android firebase firebase-realtime-database

我正在使用Android学习Firebase数据库,如下图所示在Firebase数据库中具有数据数组。

在此处输入图片说明

cineIndustry是一个数据数组。在JSON中看起来像这样

 "cineIndustry" : [ {
   "type" : "Hollywood"
 }, {
   "type" : "Kollywood"
 }, {
   "type" : "Bollywood"
 } ]
Run Code Online (Sandbox Code Playgroud)

我想在此数组中插入新数据。

POJO课程

@IgnoreExtraProperties
public class CineIndustry {

void CineIndustry(){}

public String type;

}
Run Code Online (Sandbox Code Playgroud)

保存新数据

CineIndustry cineIndustry = new CineIndustry();
cineIndustry.type = cineType.getText().toString();

mDatabase.setValue(cineIndustry);
Run Code Online (Sandbox Code Playgroud)

当我像上面那样插入时,它将替换Array。JSON结构已更改为恢复为JSON数组的普通JSON对象

任何人都知道可以帮助我解决此问题。

Ale*_*amo 5

这是因为您就是overwriting数据。您使用的是setValue()方法,而不是updateChildren()方法。

请进行以下更改,您的问题将得到解决。

因此,为了将数据对象写入Firebase数据库,而不是使用ArrayList,建议您使用Map。要保存数据,请使用以下代码:

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);
Run Code Online (Sandbox Code Playgroud)

如您所见,我updateChildren()直接在引用上调用了method。最后,数据库应如下所示:

Firebase-root
    |
    ---- cineIndustry
            |
            ---- pushedId1: "Hollywood"
            |
            ---- pushedId2: "Kollywood"
            |
            ---- pushedId2: "Bollywood"
Run Code Online (Sandbox Code Playgroud)