Rahul Giradkar
Rahul Giradkar

Reputation: 1818

Firebase Orderby Query not working

I want to used orderby score Json on w.

My Json

{  "score": {
"Abc": {
  "value": 5,
  "w": 60
},
"RRRR": {
  "value": 3,
  "w": 20
},
"Ral": {
  "value": 4,
  "w": 50
}  }}

My Android code is for fetching data of score.

  myRef.child("score").orderByChild("w").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            //  String value = dataSnapshot.getValue(String.class);
            Log.d(TAG, "Value is: " + dataSnapshot.toString());
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });

Getting the o/p as (wrong)

DataSnapshot { key = score, value = {Ral={w=50, value=4}, RRRR={w=20, value=3}, Abc={w=60, value=5}} }

I want to used order on w in on score and expect out

{  "score": {
"RRRR": {
  "value": 3,
  "w": 20
},
"Ral": {
  "value": 4,
  "w": 50
},
"Abc": {
  "value": 5,
  "w": 60
}  }}

Upvotes: 1

Views: 524

Answers (1)

John O'Reilly
John O'Reilly

Reputation: 10330

Try iterating over results like following (assuming you have Score java object corresponding to score data)

for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
    Score score = childSnapshot.getValue(Score.class);
} 

Upvotes: 2

Related Questions