java - 在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
我已经尝试过了,但它失败了。谁能指出我的错误并纠正它?
解决方案
您无法将用户的电子邮件地址作为密钥保存在 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
永远不会改变,而用户可能会更改电子邮件地址,不幸的是,您不能简单地更改密钥的名称。
推荐阅读
- java - Jersey2 遵循什么?Servlet-2 或 Servlet-3 规范
- python - 为什么 Scipy 如此糟糕地拟合这条曲线?
- setuptools - 如何在 PyPI 中设置项目链接
- java - 方法中变量的可见性
- typescript - Angular 拦截器,处理 HTTP 错误并重试
- python - 发生 SMTP 验证错误。如何解决?
- javascript - 计算来自同一 JSON 键的值的总数
- amazon-web-services - Terraform aws_codepipeline 未能满足约束
- java - 使用 Streams 获取每个子部门和部门的员工,
- python - Python上根据特定条件删除多列CSV文件