1

This is my database structure:

- Feed
       _ Parent key 1:
                - key 1:
                        _ time_stamp: 3
                - key 2:
                        _ time_stamp: 4
       _ Parent key 2:
                - key 1:
                        _ time_stamp: 2
                - key 2:
                        _ time_stamp: 1

My problem is when i'm using

Query query = mFeed.child(parent).orderByChild("time_stamp")

what i get is time_stamp ordering only on there parent key as this order

3 - 4 - 1 - 2

The order that i want to get is this :

1 - 2 - 3 - 4

Please Help !!!

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
naima
  • 129
  • 1
  • 12
  • The code you shared (`Query query = mFeed.child(parent).orderByChild("time_stamp")`) merely defines a query. There can be no problem with this code until you attach a listener to the query and try to process the results. Also: in the data you show, there is no way to get the grandchildren of both Parent key 1 and 2 in order, since Firebase queries only order over direct children. For more on this, see https://stackoverflow.com/questions/27207059/firebase-query-double-nested – Frank van Puffelen Dec 29 '18 at 05:54
  • I highly recommend updating your question to include the real minimal complet code and JSON that reproduce the problem. You can get the JSON by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Dec 29 '18 at 05:55
  • 1
    Hey @naima did my answer help you solve your problem? – PradyumanDixit Dec 30 '18 at 03:59
  • Thank you for your answer but i didn't found a solution yet. I don't know how should i structure my data to avoid this issue. – naima Dec 30 '18 at 15:15

1 Answers1

0

You need to understand that when you make a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of one result.

You can have a code like this, to do what you want:

mFeed.orderByChild("time_stamp").limitToLast(4).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                String res = childSnapshot.getValue().toString().trim();
                // do what you want by adding them to arraylist or something
            }
        } 
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // do something for errors
    }
});

Also, you don't always need to get the list from Firebase in order you want, you can order them as you like after retrieving it.

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20