gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:05 25 4
gpt4 key购买 nike

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

enter image description here

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 数据库,而不是使用 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);

如您所见,我调用了updateChildren()方法直接引用。最后,数据库应该是这样的:

Firebase-root
|
---- cineIndustry
|
---- pushedId1: "Hollywood"
|
---- pushedId2: "Kollywood"
|
---- pushedId2: "Bollywood"

关于android - 如何从 Android 在 Firebase 数据库中的现有数组中插入新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44692352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com