gpt4 book ai didi

android - 如何使用 Android 在 firebase 数据库中添加具有特定值的特定键?

转载 作者:搜寻专家 更新时间:2023-11-01 09:37:27 25 4
gpt4 key购买 nike

我有一个真实的简单 Firebase 数据库,其中有 2 个模型。一个 ListModel 和一个 UserModel。在我的列表中,我使用 push() 方法来生成唯一的 ID。我想将每个唯一 ID 添加为键和“true”,因为它在 Users/gmail@gmail,com/Lists 下的值。当我添加第一个列表时,数据库如下所示:

enter image description here

一切正常,但当我尝试添加另一个时,数据库如下所示: enter image description here

Users/gmail@gmail,com/Lists 中,第一个被第二个插入覆盖。如何添加特定 ID 和特定值作为新项目,如下所示?

enter image description here

这是我的代码:

final UserModel um = new UserModel();
um.setUserEmail("gmail@gmail,com");
userDatabaseReference.setValue(um);

ListModel lm = new ListModel();
lm.setListName(listName);
listKeyDatabaseReference = listDatabaseReference.push();
listKey = listKeyDatabaseReference.getKey();
listKeyDatabaseReference.setValue(lm);

listDatabaseReference.child(listKey).child("Users").child("gmail@gmail,com").setValue("true");
userDatabaseReference.child("gmail@gmail,com").child("Lists").child(listKey).setValue("true");

提前致谢!

最佳答案

检查 official doc :

For basic write operations, you can use setValue() to save data to a specified reference, replacing any existing data at that path.

你的问题在这里:

userDatabaseReference.setValue(um);

通过这种方式,您将覆盖 userDatabaseReference 路径中的所有子项。
这意味着 Users/gmail@gmail,com/Lists 中的第一条记录在您添加第二条记录时被删除。

使用前

userDatabaseReference.setValue(um);

您可以查看记录是否存在
如果不存在,使用 setValue 添加用户模型及其所有数据。
如果存在,则跳过此步骤,将数据添加到同一用户内的 lists 路径中。

关于android - 如何使用 Android 在 firebase 数据库中添加具有特定值的特定键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981072/

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