【问题标题】:Firebase Reatime Database datasnapshot.hasChildFirebase 实时数据库 datasnapshot.has Child
【发布时间】:2021-12-16 11:57:22
【问题描述】:

在 Firebase 实时数据库中,有数千个子节点(用户)。如果我使用snapshot.hasChild(user1) 它是一种有效的方式(我的意思是轻量级操作),还是有其他方式?

我担心的是下载所有子节点的功能。

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    DataSnapshot 是某个位置或匹配某个查询的所有数据的快照。如果您下载数千个节点来检查其中一个是否存在,那您肯定是在浪费带宽。

    您是否考虑过只加载child(user1) 的数据?

    说你现在有这个:

    myReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(user1)) {
                ...
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "Firebase:onCancelled", databaseError.toException());
        }
    };
    

    您可以通过仅加载 user1 子节点来获得相同的结果:

    myReference.child(user1).addListenerForSingleValueEvent(new ValueEventListener() {
              // ? only load the one node we care about
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) { // ? check if the snapshot exists
                ...
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "Firebase:onCancelled", databaseError.toException());
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 2021-07-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 2017-06-03
      • 2016-12-04
      • 1970-01-01
      相关资源
      最近更新 更多