Saurabh Padwekar Saurabh Padwekar -4 years ago 154
Android Question

Android - How to retrieve list of objects in their insertion order from Firebase?

What i want ?

I want to retrieve the list of objects in their insertion order from Firebase Database.

How i am adding the object to list in Firebase database ?

mRefUser.push().setValue(new MessageItem());

mRefUser.push().setValue(new MessageItem());

.

.

mRefUser.push().setValue(new MessageItem());

How its getting added ?

Firebase stores each object as key value pair in HashMap.

enter image description here

How i am retrieving these value ?

mFireBaseRefnew.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Map<String, MessageItem> messageMap = new LinkedHashMap<String, MessageItem>();
if (dataSnapshot != null && dataSnapshot.getValue() != null) {

for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
HashMap<String,MessageItem> messageMap = (HashMap<String, MessageItem>) postSnapshot.getValue();
Collection<MessageItem> messageItems = messageMap.values() ;
List<MessageItem> messageItemList = new ArrayList<MessageItem>();
messageItemList.addAll(messageItems);
}
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}
});


What i am getting ?

enter image description here

Last Note :-

The hashmap keys are in random order. Is there any way to get linked hash map instead of hashmap. i dont want to store the keys since database is maintaining the order , there should be some way to get them in the same order but i dont know how to get them.

Answer Source

Have you read documentation? Data keys is timestamp based, so they ordered by time. To get sorted query you must use orderByKey() on database reference. More about it https://firebase.google.com/docs/database/android/retrieve-data#sorting_and_filtering_data

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download