Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase sort by points depending on date

I am trying to add a monthly scoreboard but it seems to be a little bit difficult to me. I don't know how to just take a specific value to some list or array. Like Date, only date with 09.01.2017 values. If I could do that then I think that I can sort them by value.

enter image description here

        FirebaseDatabase database = FirebaseDatabase.getInstance();
    final DatabaseReference highscoreRef = database.getReference();




    // Ordering with score and adding key values as string to nameList and scoreList
    highscoreRef.orderByChild("score").limitToLast(10).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            try {

                nameList.push(snapshot.child("name").getValue().toString());
                scoreList.push(snapshot.child("score").getValue().toString());

            } catch (Exception e) {
                //Toast.makeText(getApplicationContext(), "Error fetching data.", Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }
        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }
        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getApplicationContext(), "Error sending data.", Toast.LENGTH_LONG).show();
        }

    });
like image 426
chazefate Avatar asked Jan 09 '17 16:01

chazefate


1 Answers

If you want to query date ranges, you should store them in a format that allows querying ranges. For dates that would be either a timestamp or a string that is lexicographically sortable.

You currently store dates as a dd.MM.yyyy string, which is not lexicographically sortable. I recommend switching to yyyy-MM-dd, so 2019-01-09. That way if you want to get all posts for January, you can do a range query:

ref.orderByChild("date").startAt("2017-01-01").endAt("2017-01-31")

If you already know that you want monthly leaderboard, I'd recommend changing your database structure to reflect that. So: store the scores by the month that they're in:

2017-01
  -K34761761238712
    name: "GGGG"
    score: 3
  -K4875731941298a
    name: "AAA"
    score: 1

That way you can get the high scores for January in order with:

ref.child("2017-01").orderByChild("score").limitToLast(10)
like image 126
Frank van Puffelen Avatar answered Sep 28 '22 19:09

Frank van Puffelen