Reading the documentation I understand how to pull a single value from the database but I'm not sure how to pull multiple from the same place. For example, I am looking to rank students in order of their grade. So I use orderByChild("grade") which is an int, and then I wish to get the first ten, so I use limitToLast(10) because the higher grades will be last. I am confused as to how I iterate through and push the data to the correct variables.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference gradeRef = rootRef.child("test_scores").child("english_grades");
Query gradeRef = gradeRef.orderByChild("grade").limitToLast(10);
gradeRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Handling the post
int gradeOne = 0;
int gradeTwo = 0;
int gradeThree = 0;
String studentOne = "";
String studentTwo = "";
String studentThree = "";
for (DataSnapshot ds: dataSnapshot.getChildren()) {
gradeOne = ds.child("grade").getValue(Integer.class);
gradeTwo = ds.child("grade").getValue(Integer.class);
gradeThree = ds.child("grade").getValue(Integer.class);
studentOne = ds.child("student").getValue(String.class);
studentTwo = ds.child("student").getValue(String.class);
studentThree = ds.child("student").getValue(String.class);
}
gradeOne.setText(Integer.toString(gradeOne));
gradeTwo.setText(Integer.toString(gradeTwo));
gradeThree.setText(Integer.toString(gradeThree));
studentNameTV.setText(studentOne);
studentNameTV2.setText(studentTwo);
studentNameTV3.setText(studentThree);
}
{
"test_scores" : {
"english_grades" : {
"-Lo0W8ks7WCEsrym5Qpl" : {
"name" : "Melissa",
"grade" : 88
},
"-Lo0W92WqeUMdq_y7J8M" : {
"name" : "Tom",
"grade" : 95
},
"-Lo0W9KjzXE_XCU4K8MN" : {
"name" : "Andrew",
"grade" : 89
}
}
}
}
What I want to see from my results would be StudentName = "Tom" Grade = "95" StudentName = "Andrew" Grade = "89" StudentName = "Melissa" Grade = "88".