How can I sort chat list by the most recent message?

流过昼夜 提交于 2020-12-15 05:27:11

问题


I don't know why I got stuck on a problem that the chatList is not sorting by the last message time or by the most recent message. I have tried by storing timestamp in the database and orderChildBy timestamp but it still not working.

This is the way how I created chatList in the firebaseDatabase

    val timeAgo = Date().time

    val myTimeMap = HashMap<String, Any?>()
        myTimeMap["timestamp"] = timeAgo.toString()
        myTimeMap["id"] = friendId

    val friendTimeMap = HashMap<String, Any?>()
        friendTimeMap["timestamp"] = timeAgo.toString()
        friendTimeMap["id"] = currentUserID

    val chatListSenderReference = dbRef.child("ChatList").child(currentUserID).child(friendId)
        chatListSenderReference.keepSynced(true)
        chatListSenderReference.addListenerForSingleValueEvent(object : ValueEventListener{
              override fun onCancelled(p0: DatabaseError) {
              }
              override fun onDataChange(p0: DataSnapshot) {
                       if(!p0.exists()){
                             chatListSenderReference.updateChildren(friendTimeMap)
                       }
    val chatListReceiverReference = dbRef.child("ChatList").child(friendId).child(currentUserID)
        chatListReceiverReference.updateChildren(myTimeMap)
        }
    })

on retrieving the chatlist in recyclerView

 mUsers = ArrayList()
        val userRef = dbRef.child("ChatList").child(currentUserID).orderByChild("timestamp")
        userRef.addValueEventListener(object : ValueEventListener
        {
            override fun onCancelled(error: DatabaseError) {
            }

            override fun onDataChange(snapshot: DataSnapshot)
            {
                (mUsers as ArrayList).clear()
                snapshot.children.forEach {
                    val userUid = it.key
                    if (userUid != null) {
                        (mUsers as ArrayList).add(User(uid = userUid))
                    }
                }
                retrieveGroupChatList()
                chatListAdapter?.notifyDataSetChanged()
                chatListAdapter = context?.let { ChatListAdapter(it, (mUsers as ArrayList<User>), true) }
                recyclerViewChatList.adapter = chatListAdapter
            }
        })

this is the picture of database, every time when i send or receive message timestamp get update.


回答1:


You should store the timestamp of messages and then use val chatListSenderReference = dbRef.child("ChatList").child(currentUserID).orderByChild("timestamp")




回答2:


Not sure if this will work for your case but for my Chat App, I had a list of the message and all I did is to sort the list

 //sort method - takes a list to be sorted
private fun sortMessagesByDate(messages: MutableList<Message>) {

    //sort messages by Date
    messages.sortWith(compareBy { it.timestamp })
}

Method for looping through the ContactList

 // method for obtaining contacts and adding them to the lists
private fun getAllContacts() {
    val currentUserPhoneCredential = auth.currentUser?.phoneNumber!!

    firestore.collection("Contacts")
        .whereNotEqualTo("phoneNumber", currentUserPhoneCredential)
        .get().addOnSuccessListener { querySnapshot ->
        for (doc in querySnapshot) {

            val user = doc.toObject(User::class.java)
 //I have 2 lists one with just the names and another with the User Object
            contactsList.add(user)
            contactsNames.add(user.name!!)

        }
        adapter.notifyDataSetChanged()
    }

Then on ListView's Adapter passing in the Names List(contactsNames)

 adapter =
        ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, contactsNames)

Thereafter when a name is clicked at a specific position the app navigates to the DisplayMessage Fragment taking a UserObject corresponding to the clicked contact.

//implement listView onClick
    binding.listView.setOnItemClickListener { _, _, i, _ ->


       /*when a name is clicked on the ListView at a specific position the app navigates
        to the DisplayMessage Fragment taking a UserObject corresponding to the
         clicked contact.*/
        findNavController().navigate(ChatFragmentDirections
                                         .actionChatFragmentToMessageFragment(contactsList[i]))

    }

You could also use a RecyclerView to display the names of the contacts.



来源:https://stackoverflow.com/questions/64857715/how-can-i-sort-chat-list-by-the-most-recent-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!