charbinary
charbinary

Reputation: 1895

Firebase doesn't return ordered result

I would like to take the result from Firebase ordered by "sortDate" but the actual one is randomly ordered. I would like to get the data in this order: [hip, chest, back, waist]. Here is my code:

final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("parts");

        final DatabaseReference user = myRef.child("slavi");
        user.orderByChild("sortDate");

        user.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.exists()) {

And I added an image of the firebase structure.

enter image description here

Upvotes: 0

Views: 140

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598787

When you call any of Firebase's querying method (orderBy..., startAt(), equalAt(), etc) you get back a new Query object. Your code doesn't keep a reference to that query object.

To fix this:

 final DatabaseReference user = myRef.child("slavi");
 Query query = user.orderByChild("sortDate");

 query.addListenerForSingleValueEvent(new ValueEventListener() {
      public void onDataChange(DataSnapshot dataSnapshot) {
          for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
              System.out.println(userSnapshot.getKey());
          }

Upvotes: 0

nathaniel.camomot
nathaniel.camomot

Reputation: 280

You can use dataSnapshot.getChildren() with ValueEventListener. It will loop through the child snapshots in-order. It has similar semantics to JS SDK DataSnapshot.forEach which has more detailed documentation.

for (DataSnapshot child : dataSnapshot.getChildren()) {
    Log.i(TAG, "test " + child.getValue());
}

Or you can use ChildEventListener which calls onChildAdded with each child snapshot in-order

    user.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Log.i(TAG, "test2 " + dataSnapshot.getValue());
                }

                ...

UPDATE:

I see your problem. You are not attaching the listener to the query reference.

user.orderByChild("sortDate");

user.addListenerForSingleValueEvent(new ValueEventListener() {

Should be:

   user.orderByChild("sortDate").addListenerForSingleValueEvent(new ValueEventListener() {

Upvotes: 1

Related Questions