Saransh Agarwal
Saransh Agarwal

Reputation: 305

Android: Sorting time stored in firebase database in ascending order

Hey I would like to sort time stored in firebase database as string in the ascending order and display it in a list. I have found solutions regarding sorting integer values. database

This is my database where I would like to sort according to the timeTaken by each user id at that specific question id. Edit: So my question is how can I retrieve the data from the each users uid of that specific time taken on that question id (here:982906) and sort that list to retrieve who solved the problem in the least time.

private void getTimeTaken() {

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
    Query query = databaseReference.orderByChild("questions").startAt("982906");
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            yourTimeArraylist = new ArrayList<>();
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                UserPuzzleDetails userPuzzleDetails = postSnapshot.getValue(UserPuzzleDetails.class);
                yourTimeArraylist.add(new UserPuzzleDetails(userPuzzleDetails.getYourAnswer(), userPuzzleDetails.getAnswerScore(), userPuzzleDetails.getTimeTaken()));
                Log.e("", " " + userPuzzleDetails.getTimeTaken());
            }

            for (int i = 0; i < yourTimeArraylist.size(); i++) {
                UserPuzzleDetails user = yourTimeArraylist.get(i);
                Log.d("test your rank", " onDataChange: " + user.getTimeTaken() + " " + user.getAnswerScore());

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

I have changed the values of time in the database as int in milliseconds but am unable to understand how to sort the values of question id 982906 acording to the time taken . I have tried the above method which is returning 0 everytime.

Upvotes: 0

Views: 3604

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

A Firebase Database filters the children immediately under the location that you query, based on a single property (or other condition) that you specify. The query cannot be based on a dynamic path under the child nodes.

You're nesting data in a way that doesn't allow this query: each answer is one dynamic level deeper in the tree: `/users/$uid/questions/$qid". This is one of the many reasons why the Firebase documentation recommends against nesting data in this way.

If you want to query a list of answers across all users by their "time taken", you should store precisely that in your database: a list of answers, each with their "time taken".

questionAnswers
  $questionId
    $uid
      timeTaken: "08:17:23.6"

Now you can get the 10 fastest answer for question 42 with:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference answersReference = databaseReference.child("42");
Query query = answersReference.orderByChild("timeTaken");
query.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot userAnswerSnapshot: dataSnapshot.getChildren()) {
      System.out.println("User "+userAnswerSnapshot.getKey()+" took "+userAnswerSnapshot.child("timeTaken").getValue());
    }
  }

Upvotes: 1

Maitrey C
Maitrey C

Reputation: 148

You can achieve that by creating a Data model of Answer and use comparator to sort the items by comparing dates.

Collections.sort(listItemAnswer, new Comparator<AnswerInfoDto>() { 
@Override public int compare(AnswerInfoDto l, AnswerInfoDto r) 
{ // Compare l.timeTaken and r.timeTaken} }

Edit To match with your case, you will have to parse the time string with SimpleDateFormat before comparing dates as below :

class StringDateComparator implements Comparator<String>
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
    public int compare(String lhs, String rhs)
    {
        return dateFormat.parse(lhs).compareTo(dateFormat.parse(rhs));
    }
}

Collections.sort(arrayList, new StringDateComparator());

Upvotes: 0

Related Questions