0

I saved the data into Fire base but when I retrieve it. The data is not in the sequence.

Here Data Is Saved In Accurate Sequence: Here Data Is Saved In Accurate Sequence

But when I retrieve data lost its sequence:

In It Data Lost Its Sequence

Here is my code for retrieving Data

 DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users").child(Autho_User.getUid()).child("Data");
            ref.addListenerForSingleValueEvent(
                    new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {



                           System.out.println(" Value = "+dataSnapshot.toString()); 
}

(Printed it just to check values) Data is not in the sequence even I get it through

 dataSnapshot.getvalue();

Hope so you got my question. I need the data in sequence

KENdi
  • 7,576
  • 2
  • 16
  • 31

1 Answers1

0

Firebase stores JSON data. By definition the children under a node in JSON are unordered. It is only when the data is displayed or retrieved that it gets an order. So the first screenshot that you show is just the order in which the Firebase Database console display it.

If you want to get the data in a specific order in your application, you need to do two things:

  1. Execute a query that returns the data in that order.
  2. Ensure that your code maintains that order.

The code you shared does neither 1 nor 2, so the order in which the data is printed is anybody's guess. Usually it will be in lexicographical order of the keys, but it is undefined.

To learn how to order/filter data, read the Firebase documentation on ordering and filtering. To learn how to maintain the order of items when you use a ValueEventListener, read the Firebase documentation on listening for value events. When you combine these two, you get:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users").child(Autho_User.getUid()).child("Data");
Query dataOrderedByKey = ref.orderByKey();
dataOrderedByKey.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            System.out.println("Key = "+childSnapshot.getKey()+" Value = "+childSnapshot.toString()); 
        }
    }
    ...

This is an incredibly common mistake/question, so here are some previous questions for reference:

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