2

My Firebase Database is like this

Firebase Database

When the coding below was run:

String loc=(snapshot.child("loc").getvalue()).tostring();

The output I get has different sequence with the database:

Output

Why is that so?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
jwen
  • 145
  • 2
  • 15

2 Answers2

3

Firebase data is stored as JSON and is inherently unordered.

If you want to access the data in a specific order, you should specify an orderBy clause for your query and access the data using the snapshot's getChildren() method.

Say you want to log the items by ascending key:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getRef();
Query locations = rootRef.orderByKey();
locations.addListenerForSingleValueEvent(new ValueEventListener() {
  public void onDataChange(DataSnapshot snapshot) {
    for (DataSnapshot locSnapshot: snapshot.getChildren()) {
        System.out.println(locSnapshot.getKey() + ": " + locSnapshot.getValue(String.class));
    }
  }

  public void onCancelled(DatabaseError databaseError) {
    Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
    // ...
  }
});

This sample comes (modified) from the Firebase documentation on reading lists of data.

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

Frank beat me to my edit, check out his correct solution using orderBy....


You need to use forEach rather than the child method (or child.foreach)

Here is a snippet from the doc:

Because of the way JavaScript Objects work, the ordering of data in the JavaScript Object returned by val() is not guaranteed to match the ordering on the server nor the ordering of child_added events. That is where forEach() comes in handy. It guarantees the children of a DataSnapshot will be iterated in their query-order.

Source: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#forEach

sorifiend
  • 5,927
  • 1
  • 28
  • 45