skip to Main Content

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".

2

Answers


  1. 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()
            }
        })
    }
    
    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search