首页 > 解决方案 > 在firebase(JAVA)中插入一个字符串变量作为键(子)

问题描述

我已经阅读了 Firebase 的官方文档,但我仍然对如何将字符串变量作为孩子插入并设置该孩子的值感到困惑。我需要动态的键。目前,我正在尝试实现这一点 -

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String email = "abc@example.com";

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dbRef = database.getReference("connections").child(uid);
dbRef.child(email).setValue("true");

理想情况下,这应该使用当前 uid 在表“connections”内创建一个新节点,在该节点内创建一个子属性“abc@example.com”并将值设置为 true。像这样-

\connections
  -uid
   -abc@example.com: true

我已经尝试过了,但它失败了。谁能指出我的错误并纠正它?

标签: javaandroidjsonfirebasefirebase-realtime-database

解决方案


您无法将用户的电子邮件地址作为密钥保存在 Firebase 实时数据库中,因为它包含诸如.. 如果您仍想使用电子邮件地址,我建议您将其编码如下:

name@email.com -> name@email,com

正如您可能看到的那样,.我使用了,. 为此,您可以使用以下方法:

static String encodeUserEmail(String userEmail) {
    return userEmail.replace(".", ",");
}

static String decodeUserEmail(String userEmail) {
    return userEmail.replace(",", ".");
}

但是,更合适的方法是使用uid来自身份验证过程的 。主要好处是uid永远不会改变,而用户可能会更改电子邮件地址,不幸的是,您不能简单地更改密钥的名称。


推荐阅读