Home > front end >  Firebase: get children ordered by Date and Hour keys
Firebase: get children ordered by Date and Hour keys

Time:03-06

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: DB structure

So the order of the output I would like to get is:

  1. History, 14:00
  2. History, 9:00
  3. Math, 12:00
  4. 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?

CodePudding user response:

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.

  • Related