首页 > 解决方案 > 如何从 Firebase 数据库中的子项检索特定数据

问题描述

我是 Firebase 数据库的新手,我在 Firebase 中的数据结构是这样的:

Root- users-sec_a, sec_b, sec_c

在每个部分(sec_a,sec_b,sec_c)中都会有用户的 uid。在每个部分中至少有 40 个 uid。并且在所有 uid 中都有一个公共数据子项(姓名、rollno、出席)现在我的问题是我只想显示其中一个部分中存在的所有 uid 的名称和 rollno(要显示的部分是由用户输入的)。

我怎样才能得到这些数据?

标签: javaandroidfirebasefirebase-realtime-database

解决方案


这很容易。

String sectionSelectedByUser = "sec_a"; // For example

现在获得firebase数据库的引用

if (FirebaseAuth.getInstance().getCurrentUser() != null){ // if you need user to be signed in.. 
            FirebaseDatabase.getInstance().getReference().child("users").child(sectionSelectedByUser).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) { // iterates through all your UID in this section
                        if (childSnapshot.hasChild("name")){ // if current uid has name then fetch it
                            String name = childSnapshot.child("name").getValue().toString();
                        }

                        if (childSnapshot.hasChild("rollno")){ // if current UID has rollno then fetch it
                            String rollno =  childSnapshot.child("rollno").getValue().toString();
                        }
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }

推荐阅读