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

后端 未结 4 431
别跟我提以往
别跟我提以往 2021-01-14 11:47

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

相关标签:
4条回答
  • 2021-01-14 12:18

    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

    0 讨论(0)
  • 2021-01-14 12:22

    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

    0 讨论(0)
  • 2021-01-14 12:40

    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 = new TreeMap<>();
    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.

    0 讨论(0)
  • 2021-01-14 12:42

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

    mFireBaseRefnew.orderByKey().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) {
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题