You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Firebase获取指定用户的嵌套子节点数据

解决Firebase获取特定用户数据并在RecyclerView展示的问题

根据你的需求,要在RecyclerView中只展示特定用户的邀请数据,有两种可行方案,优先推荐数据库端过滤的方式:

方法一:Firebase数据库端过滤(推荐)

直接在查询阶段筛选出目标用户的数据,减少不必要的数据传输。假设你的邀请节点中包含invitedUid字段(对应用户ID),可以通过orderByChild和equalTo实现精准查询:

// 获取当前登录用户的ID(需确保已通过Firebase Auth完成登录)
String currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();

DatabaseReference notificationInviteRef = FirebaseDatabase.getInstance().getReference().child(Strings.InvitesReference);
// 按invitedUid字段筛选,仅获取当前用户的邀请数据
Query userInvitesQuery = notificationInviteRef.orderByChild("invitedUid").equalTo(currentUserId);

userInvitesQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot1) {
        ArrayList<Model_Notifications_Invite> model_notification_invites = new ArrayList<>();
        for (DataSnapshot snapshot2 : snapshot1.getChildren()) {
            Model_Notifications_Invite invites = snapshot2.getValue(Model_Notifications_Invite.class);
            model_notification_invites.add(invites);
        }
        myNotificationsAdapter.updateNotificationsList(model_notification_invites);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // 打印错误信息方便调试
        databaseError.toException().printStackTrace();
    }
});

注意事项:

  • 确保Model_Notifications_Invite类中存在与数据库键名一致的字段(比如invitedUid),且有对应的getter/setter方法。
  • 在Firebase控制台的数据库规则中,需允许对invitedUid字段的查询权限,或者设置规则让用户仅能访问自己的数据。

方法二:本地数据过滤

如果无法在数据库端过滤(比如数据结构限制),可以先获取所有数据,再在本地筛选出目标用户的内容:

DatabaseReference notificationInviteRef = FirebaseDatabase.getInstance().getReference().child(Strings.InvitesReference);
notificationInviteRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot1) {
        ArrayList<Model_Notifications_Invite> model_notification_invites = new ArrayList<>();
        String currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        
        for (DataSnapshot snapshot2 : snapshot1.getChildren()) {
            Model_Notifications_Invite invites = snapshot2.getValue(Model_Notifications_Invite.class);
            // 假设invites对象有getInvitedUid()方法获取被邀请用户ID
            if (invites != null && currentUserId.equals(invites.getInvitedUid())) {
                model_notification_invites.add(invites);
            }
        }
        myNotificationsAdapter.updateNotificationsList(model_notification_invites);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        databaseError.toException().printStackTrace();
    }
});

这种方式会下载所有邀请数据,仅适合数据量较小的场景,数据量大时推荐用第一种方法。

内容的提问来源于stack exchange,提问作者greenTea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:06:29