如何从Android在Firebase数据库的现有数组中插入新数据? [英] How to Insert new data in existing array in Firebase Database from Android?

查看:62
本文介绍了如何从Android在Firebase数据库的现有数组中插入新数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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类

@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数组.

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.

推荐答案

之所以发生这种情况,是因为您是overwriting数据.您正在使用setValue()方法,而不是使用updateChildren()方法.

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.

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

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);

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

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"

这篇关于如何从Android在Firebase数据库的现有数组中插入新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆