【问题标题】:How to get a child value if another child value matches in Firebase?如果 Firebase 中的另一个子值匹配,如何获取子值?
【发布时间】:2021-08-04 10:27:30
【问题描述】:

我的数据库结构是:

{
"Users" : {
"KTTbTIq2A4aZcjKPSYlZhrBiDwD3" : {
  "Email" : "g2@g.com",
  "ID" : "KTTbTIq2A4aZcjKPSYlZhrBiDwD3",
  "UserName" : "GokulNew2"
},
"ovxZPZeyy2VlZUP1K0vv9VtiThu1" : {
  "Email" : "g1@g.com",
  "ID" : "ovxZPZeyy2VlZUP1K0vv9VtiThu1",
  "UserName" : "GokulNew1"
   }
  }
}

在这个结构中,如果“UserName”与“GokulNew1”匹配,我需要将“ID”(自动生成)作为“ovxZPZeyy2VlZUP1K0vv9VtiThu1”获取。我需要将 ID 存储在 String ID 中。

我的代码是,

private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
String Id;
String Name = "GokulNew1";

reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            recyclerId= snapshot.child("ID").toString();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            throw error.toException();
        }
    });

【问题讨论】:

  • 我真的不明白接受的答案将如何工作?你能提供一些细节吗?提供的代码确实不完整。 “在此处检查 id”如何工作?此外,使用 addListenerForSingleValueEvent 有什么意义?这种方法,现在被认为是旧的有利于最近添加的新 get() 方法? “不要忘记向 Firebase 规则添加查询”是什么意思?在我看来,这个答案可能只会让未来的访客感到困惑。这根本没有任何意义!

标签: java android firebase firebase-realtime-database


【解决方案1】:

如果“UserName”与“GokulNew1”匹配,则要获取节点的密钥(ovxZPZeyy2VlZUP1K0vv9VtiThu1),请使用以下代码行:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
Query queryByUserName = usersRef.orderByChild("UserName").equalTo("GokulNew1");
queryByUserName.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot uidSnapshot : task.getResult().getChildren()) {
                String uid = uidSnapshot.getKey();
                Log.d("TAG", uid); //Do what you need to do with the uid
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

logcat 中的结果将是:

ovxZPZeyy2VlZUP1K0vv9VtiThu1

【讨论】:

  • 嗨,亚历克斯收到错误,因为索引未定义,将“.indexOn”:“用户名”,路径“/用户”添加到规则中并且此错误在几秒钟后不会永久存在,它正在工作很好。
  • 您是否尝试过创建索引,也就是说它在抱怨?
  • 在哪里添加 Alex?
  • 在安全规则中。您可以查看this
  • 但我仍然不明白这个接受的答案是如何工作的。你能提供一些细节吗?
【解决方案2】:

您需要使用此添加查询以将其与特定字符串匹配。它只会返回该项目,否则简单的 fetch 将有列表。

Query query = reference.orderByChild("UserName").equalTo("GokulNew1");
query.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot){ 
   //Check for id here.
  }

不要忘记向 firebase 规则添加查询。

【讨论】:

  • 这个工作正常,感谢 Chanpreet Singh
猜你喜欢
  • 2017-09-03
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多