3

I am doing everything as per documentation but don't know why I am not getting ordered data

My Query

 typeRef = myRef.child("DiscussionRooms").orderByChild("order");
     valueEventListener = typeRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (dataSnapshot.getValue() != null) {

                Log.d(TAG, "Get Data" + dataSnapshot.getValue().toString());

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

My Database

enter image description here

My Database Rules

enter image description here

Response Logs

enter image description here

Monu
  • 877
  • 1
  • 9
  • 27
  • 1
    When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. You need to loop over `dataSnapshot.getChildren()` to get the results in the correct order, as Alex' answer shows or one of these: https://stackoverflow.com/q/37808965 and https://stackoverflow.com/a/42687205 – Frank van Puffelen Jun 08 '18 at 17:11

1 Answers1

6

To display the data ordered according to the order property, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference discussionRoomsRef = rootRef.child("DiscussionRooms");
Query orderQuery = discussionRoomsRef.orderByChild("order");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            Log.d("TAG", name);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
    }
};
orderQuery.addListenerForSingleValueEvent(valueEventListener);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193