【问题标题】:Check Mutiple values into Firebase and Retrive respected Node将多个值检查到 Firebase 并检索受尊重的节点
【发布时间】:2020-05-02 00:26:41
【问题描述】:

我在 Map 对象中有联系人列表,我想将每个联系人与 Firebase 进行比较,如果联系人作为值匹配,则检索该节点。

例如:假设我有 123,345,567 个联系人作为 3 个联系人,如果节点内有联系人,我想获得该完整节点。

Firebase 结构

-Users
    -someId1
        -contact:123
        -fname:something
    -someId2
        -contact:345
        -fname:something
    -someId3
        -contact:567
        -fname:something
    -someId4
        -contact:980
        -fname:something

如果给定的联系人匹配到 Firebase 节点,我如何检索这些完整的节点。

我写过这样的东西

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference reference=rootRef.child("Users");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (Map.Entry<String, String> singleContact : contacts.entrySet()) {
            query=reference.orderByChild("contact").equalTo(singleContact.getKey());
            if (dataSnapshot.hasChild(singleContact.getKey()))
                userModelObjects.add(dataSnapshot.child(singleContact.getKey()).getValue(FirebaseUserModel.class));

        }
}

【问题讨论】:

  • 如何将这些联系人存储到数组中?是否有可能有超过三个可以比较的联系人?
  • 我将每个映射键与 Firebase 进行比较,并添加到 FirebaseUserModel 类的 ArrayList 中。 Map 对象中可以有 n 个联系人。
  • 1) 您当前的代码有什么问题? 2) 如果您的用户已经有自己的唯一 ID,为什么不使用该 ID 作为数据库中的键?这将使查找用户更容易。
  • 告诉我如何使用查询迭代不同的联系人。我将修复其余代码。

标签: android firebase firebase-realtime-database


【解决方案1】:

我假设keys in your map 就像keys in your database

//your reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");

//make a listener

ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

     //this loop will extract all the values in every random ID

     for(DataSnapshot ds : dataSnapshot.getChildren()){

     //extract the values

     String contact = ds.child("contact").getValue(String.class);
     String fname = ds.child("fname").getValue(String.class);

     //check if they exist in the map, and see what you can do.........


    }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
     //error getting data
    }
};
ref.addValueEventListener(listener);

【讨论】:

  • 优秀的解决方案。感谢您的帮助
猜你喜欢
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多