Skip to content Skip to sidebar Skip to footer

Android - How To Retrieve List Of Objects In Their Insertion Order From Firebase?

What do I want? I want to retrieve the list of objects in their insertion order from Firebase Database. How am I adding the object to list in Firebase database? mRefUser.push().se

Solution 1:

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

Solution 2:

If you are having HashMap inside class and want to get whole firebase object using getValue(Classname.class)

Method bellow will help you

get it into TreeMap from HashMap and you'll have ordered list as in firebase by key

Example code

TreeMap<String,Recordings> recordingsTreeMap = newTreeMap<>();
recordingsTreeMap.putAll(project.getRecordings());

You will have ordered list by key in TreeMap object.

where project is a class having multiple fields and one or more HashMap and you don't want to query each separately.

Solution 3:

Here is an example to illustrate Mr. Dima Rostopira response more clearly. Do you see the "orderByKey()"?

mFireBaseRefnew.orderByKey().addValueEventListener(newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        final Map<String, MessageItem> messageMap = newLinkedHashMap<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 = newArrayList<MessageItem>();
                messageItemList.addAll(messageItems);                     
        }
    }

    @OverridepublicvoidonCancelled(FirebaseError firebaseError) {

    }
});

Solution 4:

To retrieve sorted data, start by specifying one of the order-by method. For more https://firebase.google.com/docs/database/android/lists-of-data

Post a Comment for "Android - How To Retrieve List Of Objects In Their Insertion Order From Firebase?"