Reputation: 44
Query used:
q = FirebaseDatabase.getInstance().getReference().child("products").orderByChild("timestamp");
q.addValueEventListener(new ValueEventListener() {
@Override
public void onCancelled(DatabaseError databaseError) {
}
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("datasnapshot", dataSnapshot.toString());
This value is in my Firebase database in same order.
Note: I am using negative value approach { -1 * new Date().getTime();}
to store timestamp.
This value is in my Firebase database in same order:
Ke7K4vXyEt4gKnjf68H
timestamp: -1488345920790
Ke7KB2F1UKh8LoWcCY3
timestamp: -1488345945825
KeHlQIBnOE3diP8Wksh
timestamp: -1488521122407
KeI9nJtt4eg5Vd0rcAv
timestamp: -1488527774123
KeWwWW_ezG-cjmF8TNO
timestamp: -1488775680799
KeX7G0WOVidrMBbuGiT
timestamp: -1488778758960
Keg3mtNpyKStpVMMvRm
timestamp: -1488945623757
Keg4fN3rAN7uy5weFJz
timestamp: -1488945855094
Below order is what I get when I print the datasnapshot:
KeX7G0WOVidrMBbuGiT
timestamp: -1488778758960
Keg3mtNpyKStpVMMvRm
timestamp: -1488945623757
Keg4fN3rAN7uy5weFJz
timestamp: -1488945855094
Ke7K4vXyEt4gKnjf68H
timestamp: -1488345920790
KeWwWW_ezG-cjmF8TNO
timestamp: -1488775680799
KeHlQIBnOE3diP8Wksh
timestamp: -1488521122407
Ke7KB2F1UKh8LoWcCY3
timestamp: -1488345945825
KeI9nJtt4eg5Vd0rcAv
timestamp: -1488527774123
Upvotes: 0
Views: 836
Reputation: 598817
When you execute a query against the Firebase Database, it returns three pieces of information for each matching node:
When you print the snapshot, you're actually printing a Map<String, Object>
of the query result. And in a map there is only space for two pieces of information: the key of each node and the value of that node. So the order of the nodes is lost when you print the result.
For that reason you should iterate over the children of the result with the built-in getChildren()
method of the snapshot:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("datasnapshot", child.getKey()+": "+child.getValue());
}
}
And with this you will see the children in the order of their timestamp.
If you want to keep them in a list (so that the order is maintained), I recommend simply keeping a list of snapshots:
public void onDataChange(DataSnapshot dataSnapshot) {
List<DataSnapshot> list = new LinkedList<DataSnapshot>();
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("datasnapshot", child.getKey()+": "+child.getValue());
list.add(child);
}
}
Upvotes: 1