且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不下载孩子的情况下从Firebase获取孩子密钥?

更新时间:2023-09-10 19:58:22

要获取这些用户的ID,请使用以下代码:

To get the ids of those users, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String uid = ds.getKey();
            Log.d("TAG", uid);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);

输出将是:

5Aoz6ZaB9QS7o9M4lsdbh07VGA02
// the other ids

在特定节点上附加侦听器时,将获得该节点下的所有数据.这就是Firebase Realtime数据库的工作方式,令人遗憾的是,无法更改此行为.但是有一种解决方法,您可以创建另一个单独的节点,在其中可以单独添加所有这些ID.新节点应如下所示:

When you attach a listener on a specific node, you get all the data beneath that node. This is how Firebase Realtime database works and unfortanately this behaviour cannot be changed. But there is an workaround in which you can create another separate node in which you can add all those ids separately. The new node should look something like this:

Firebase-root
   |
   --- userIds
          |
          --- 5Aoz6ZaB9QS7o9M4lsdbh07VGA02: true
          |
          --- //other ids

在这种情况下,如果在 userIds 节点上附加侦听器,则只会获得所需的数据,仅此而已.获取这些ID的代码与上面的代码类似,但是除了使用 .child("users")之外,您还需要使用 .child("userIds").输出将是相同的.

In this case, if you attach a listener on userIds node, you'll get only the desired data and nothing more. The code to get those ids is simmilar with the code above, but instead of using .child("users") you need to use .child("userIds"). The output will be the same.

如果您想要其他行为,可以考虑使用 Cloud Firestore ,在这种情况下不再是问题了.

If you want another behaviour, you can consider using Cloud Firestore where this behaviour isn't an issue anymore.