Issue
I have stored in my Firestore DB data about Teachings and their relative Lessons, with Date and Hour. I would like to retrieve this data ordered by Date and Hour (the ones that have most recent Date and Hour should be retrieved first), but since these two fields are not values, but keys, I don't know how to do it. I then add these data into an ArrayList of lessons that I use to show everything into a RecyclerView. This is my DB structure:
So the order of the output I would like to get is:
- History, 14:00
- History, 9:00
- Math, 12:00
- Math, 9:00
With the code below I've just retrieved every lesson in alphabetical order.
FirebaseAuth mAuth;
FirebaseUser user;
mAuth = FirebaseAuth.getInstance();
user= mAuth.getCurrentUser();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("Teachings").child(user.getUid());
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot dataCourse: dataSnapshot.getChildren()){
String course= dataCourse.getKey();
for(DataSnapshot dataDate: dataCourse.getChildren()){
String date= dataDate.getKey();
for(DataSnapshot dataHour: dataDate.getChildren()){
String hour= dataHour.getKey();
lessonsArrayList.add(new Lesson(course, date, hour));
}
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
The class Lesson:
public class Lesson {
public String courseName, date, hour;
public Lezione(String courseName, String date, String hour){
this.courseName= courseName;
this.date= date;
this.hour=hour;
}
}
Can someone help me?
Solution
While the Firebase Realtime Database can order its results, the values to order on must be at a fixed path under each direct child node.
In your case the value is under a $date/$time
of each child node, so the database can't order on those values. You will have to load the into your application code first, and sort them there.
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.