Home > OS >  Order Queries in Firestore by the numbers given in the document into recyclerView Using Kotlin
Order Queries in Firestore by the numbers given in the document into recyclerView Using Kotlin

Time:10-31

I have already got the data from firestore into recyclerView.

Now i want to order those documents by the numbers which is in each documents.

The document which has the highest number must be in top , And document which has the lowest number must be in below of the recyclerView.

my code which i used to retrieve data from firestore `

private fun eventChangeListener() {
    db = FirebaseFirestore.getInstance()
    db.collection("posts").orderBy("hike",Query.Direction.ASCENDING)
        .addSnapshotListener(object : EventListener<QuerySnapshot>{
            override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {

                if (error != null){
                    Log.e("Firestore Error",error.message.toString())
                    return
                }

                for (dc: DocumentChange in value?.documentChanges!!){
                    if (dc.type == DocumentChange.Type.ADDED){
                        userArrayList.add(dc.document.toObject(User::class.java))
                    }

                }
                adapter.notifyDataSetChanged()


            }


        })
}

`

numbers of the documents are given in the field "hike".

CodePudding user response:

You are using the wrong order direction, it should be "Descending"

private fun eventChangeListener() {
db = FirebaseFirestore.getInstance()
db.collection("posts").orderBy("hike",Query.Direction.DESCENDING)
    .addSnapshotListener(object : EventListener<QuerySnapshot>{
        override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) {
            if (error != null){
                Log.e("Firestore Error",error.message.toString())
                return
            }
            for (dc: DocumentChange in value?.documentChanges!!){
                if (dc.type == DocumentChange.Type.ADDED){
                    userArrayList.add(dc.document.toObject(User::class.java))
                }
            }
            adapter.notifyDataSetChanged()
        }
    })
}

CodePudding user response:

It should be:

orderBy("hike",Query.Direction.DESCENDING)

There is another way too, you can order after you get data.

userArrayList = userArrayList.sortByDescending { it.hike }
// this will do the trick.
adapter.notifyDataSetChanged()
  • Related