我正在使用Android学习Firebase数据库,在Firebase数据库中具有数据数组,如下图所示。
cineIndustry 是一个数据数组。在 JSON 中,它看起来像这样
"cineIndustry" : [ {
"type" : "Hollywood"
}, {
"type" : "Kollywood"
}, {
"type" : "Bollywood"
} ]
我想在此数组中插入新数据。
POJO类
@IgnoreExtraProperties
public class CineIndustry {
void CineIndustry(){}
public String type;
}
保存新数据
CineIndustry cineIndustry = new CineIndustry();
cineIndustry.type = cineType.getText().toString();
mDatabase.setValue(cineIndustry);
当我像上面那样插入时,它将替换Array。 JSON结构已更改为从 JSON数组复原的普通 JSON对象。
任何人都知道可以帮助我解决此问题。
最佳答案
发生这种情况是因为您正在对数据进行overwriting
。您正在使用setValue()
方法,而不是使用updateChildren()
方法。
请进行以下更改,您的问题将得到解决。
因此,为了将数据对象写入Firebase数据库,建议不要使用Array
或List
,而建议您使用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);
如您所见,我直接在引用上调用了
updateChildren()
方法。最后,数据库应如下所示:Firebase-root
|
---- cineIndustry
|
---- pushedId1: "Hollywood"
|
---- pushedId2: "Kollywood"
|
---- pushedId2: "Bollywood"