Saturday, 28 November 2020

Sort chat-list by the most recent message with firebase

I don't know why I got stuck in a problem that the chatList is not sorting by the last message time or by the most recent message. I have tried storing timestamp in the database and orderChildBy timestamp but it still not working. not working means the list get not sort after every message and keep showing the list as the sorted after first message.

Look at the image how chats are disordered!

enter image description here

This is the way I created chatList in the firebaseDatabase in ChatActiviy on sendMessage:

    val timeAgo = Date().time

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

    val friendTimeMap = HashMap<String, Any?>()
        friendTimeMap["timestamp"] = timeAgo
        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, I am trying to get the users details for each userswho is presented as the child of currentUser in database. (Chatlist>>CurrentUserId)

 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)) }
                    }
                    chatListAdapter?.notifyDataSetChanged()
                    chatListAdapter = context?.let {ChatListAdapter(it,(mUsers as ArrayList<User>),true)}
                    recyclerViewChatList.adapter = chatListAdapter}
                })

And this is the chatListAdapter for friend info

private fun friendInfo(fullName: TextView, profileImage: CircleImageView, uid: String) {
        val userRef = FirebaseFirestore.getInstance().collection("Users").document(uid)
        userRef.get()
                .addOnSuccessListener {
                    if (it != null && it.exists()) {
                        val user = it.toObject(User::class.java)
                Picasso.get().load(user?.getImage()).placeholder(R.drawable.default_pro_pic).into(profileImage)
                fullName.text = user?.getFullName()
            }
        }
    }

This is the picture of the realtime database and has a model class as ChatList, every time when I send or receive a message timestamp gets an update.

ChatList

and the second picture is of users in the firestore and has a model class as User.

  1. Users image in Firestore.


from Sort chat-list by the most recent message with firebase

2 comments: