0

I am using firebase in my android application and my tree looks like this

data > tanks > username1 > kills = 1, tries = 3
             > username5 > kills = 5, tries = 13
             > username7 > kills = 3, tries = 7
             > username2 > kills = 6, tries = 4

data > cannons > username9 > kills = 31, tries = 33
               > username7 > kills = 15, tries = 13
               > username3 > kills = 13, tries = 77
               > username6 > kills = 66, tries = 44

what i am trying to do is show the user the top 10 usernames with the highest kills for cannons or tanks (depending on which one the user selects) but i cant seem to find a solution.

At first i thought the solution would be like

ref.child("data/tanks").orderbyChild("kills")

but it doesn't seem to work the problem is that it doesn't return the "kills" child. it returns the whole tree of the tank which i can already access. What i want is to get a list of all "kills" child if that's possible? And i am not sure how else can i get the highest kills because there's no way of knowing which of the usernames are in tanks or cannons unless i iterate through all of the usernames.

Can anyone help me with this?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
LazyDev
  • 15
  • 1
  • 8

2 Answers2

0
         DatabaseReference myref= FirebaseDatabase.getInstance().getReference().chield("tanks");
         myref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            userlist= new ArrayList<String>();

            Toast.makeText(DataFromFirebase.this, "no of usersare " + dataSnapshot.getChildrenCount(), Toast.LENGTH_LONG).show();
            //String value = (String) dataSnapshot.getValue();

            // Result will be holded Here
            for (DataSnapshot dsp : dataSnapshot.getChildren()) {
                userlist.add(String.valueOf(dsp.getKey())); /
                 }
           @Override
              public void onCancelled(DatabaseError firebaseError) {

             }
          }

using above code you get the all users in tanks chield then repeat this for all user references then get all kill values

Narender Reddy
  • 463
  • 6
  • 18
  • Thank you for your reply. That is not the problem however, the problem is that it doesn't return the "kills" child. it returns the whole tree of the tank. – LazyDev Aug 22 '16 at 10:08
  • here userlist consist chields of tank i.e.,user1,user 5,user 7,user 2 – Narender Reddy Aug 22 '16 at 10:26
0

It's a bit hard to be sure, but I think you're looking for limitToLast():

var topScorers = ref.child("data/tanks").orderbyChild("kills").limitToLast(10);

Then use the code from Narender's answer to loop over the players.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807