Firebase Data Desc Sorting in Android

前端 未结 15 2353
醉话见心
醉话见心 2020-11-22 07:51

I am storing data in Firebase storage.

Object Comment with attribute timestamp. When I push data from device to Firebase I\'m populating

15条回答
  •  自闭症患者
    2020-11-22 08:28

    Based on Himanshus answer but Im using kotlin and instead of the timestamp in the question Im ordering by score which should be similar. I'm not sure if firebase has an ascending or descending function but this is what ended working for me in my current project. I hope it will help someone else in the near future.

    FirebaseFirestore.getInstance().collection("leaderboard")
                .orderBy("score")
                .addSnapshotListener { snapshot, exception ->
    
                    if (exception != null) {
                        Log.e("Exception:", "Could not retrieve scores ${exception.localizedMessage}")
                    }
    
                    if (snapshot != null) {
                        scores.clear()
    
                        for (document in snapshot.documents) {
                            val data = document.data
    
                            val name = data?.get("name") as? String
                            val score = data?.get("score") as? Number
    
                            val documentId = document.id
    
                            val newScore = Score(name, score, documentId)
                            scores.add(newScore)
                        }
    
                        scores.reverse()
                        scoresAdapter.notifyDataSetChanged()
                    }
                }
    

    This is what worked for me. Happy coding!

提交回复
热议问题