Saransh Agarwal
Saransh Agarwal

Reputation: 305

Sorting in ascending order not working Firebase

Hey I am trying to sort my data in ascending order but the data is getting displayed in the order of how they are stored in the database:

This is the function being used to sort the data to find the least time.

    private void getTimeTaken1(final String name) {
    final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("users");
    final Query query = databaseReference1.orderByChild("timeTaken").limitToLast(10);

    Log.e(TAG, "getTimeTaken1: " + name);
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int rank = 1;
            for (DataSnapshot userAnswerSnapshot : dataSnapshot.getChildren()) {
                if (yourTimeArraylist.size() < 10) {
                    if (userAnswerSnapshot.child("questions").child(name).hasChild("timeTaken")
                            && userAnswerSnapshot.child("questions").child(name).child("checkAnswerCorrect").getValue(String.class).equals("1")) {

                        Log.e("", "User " + " " + userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue().toString());


                        yourTimeArraylist.add(new PreviousDayRank(userAnswerSnapshot.child("random").getValue(String.class),
                                userAnswerSnapshot.child("name").getValue(String.class),
                                timetaken(userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue(Integer.class)),
                                rank));
                        Log.e("", "onDataChange: user" + userAnswerSnapshot.child("questions").child(name).child("timeTaken").getValue());
                        rank++;

                    } else {
                        yourTimeArraylist.add(new PreviousDayRank(userAnswerSnapshot.child("random").getValue(String.class), userAnswerSnapshot.child("name").getValue(String.class), "-", rankl̥));

                        rank++;
                    }

                }

            }

            query.removeEventListener(this);
            databaseReference1.removeEventListener(this);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Upvotes: 0

Views: 358

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Your DatabaseReference is wrong. Please use this code:

final DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference().child("users").child(userId).child("questions").child(questionNumber);
final Query query = databaseReference1.orderByChild("timeTaken").limitToLast(10);

Where userId and questionNumber are the id's generated by push() method and the second by you.

Hope it helps.

Upvotes: 1

Related Questions