根据您的评论,可能的数据库结构如下:
Firebase-root
|
--- teachers
| |
| --- teacherIdOne
| | |
| | --- "teacherName" : "Teacher Name One"
| | |
| | --- students:
| | |
| | --- studentIdOne: "Student Name One"
| | |
| | --- studentIdTwo: "Student Name Two"
| |
| --- teacherIdTwo
| |
| --- "teacherName" : "Teacher Name Two"
| |
| --- students:
| |
| --- studentIdThree: "Student Name Three"
| |
| --- studentIdFour: "Student Name Four"
|
--- students
|
--- studentIdOne
| |
| --- "studentName" : "Student Name One"
|
--- studentIdTwo
| |
| --- "studentName" : "Student Name Two"
|
--- studentIdThree
| |
| --- "studentName" : "Student Name Three"
|
--- studentIdFour
| |
| --- "studentName" : "Student Name Four"
|
--- studentIdFive
|
--- "studentName" : "Student Name Five"
要显示所有5名学生的姓名,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentsRef = rootRef.child("students");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String studentName = ds.child("studentName").getValue(String.class);
Log.d("TAG", studentName);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
studentsRef.addListenerForSingleValueEvent(valueEventListener);
Te输出将为:
Student Name One
Student Name Two
Student Name Three
Student Name Four
Student Name Five
如果您有兴趣将这些名称显示在
RecyclerView
,则,
this
是如何从Firebase实时数据库中检索数据并将其显示在
回收视图
使用
FirebaseRecyclerAdapter
.
如果要显示特定教师的学生,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentsRef = rootRef.child(teachers).child(teacherId).child("students");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String studentName = ds.getValue();
Log.d("TAG", studentName);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
studentsRef.addListenerForSingleValueEvent(valueEventListener);
其中
teacherId
是要显示其学生的教师id。例如,如果教师的id为
teacherIdOne
,输出将为:
Student Name One
Student Name Two