가장 최근 메시지를 기준으로 채팅 목록을 정렬하려면 어떻게해야합니까?
Nov 16 2020
chatList 가 마지막 메시지 시간이나 가장 최근 메시지를 기준으로 정렬되지 않는 문제에 갇힌 이유를 모르겠습니다 . 나는 timestamp
데이터베이스와 orderChildBy 타임 스탬프 에 저장하려고 시도 했지만 여전히 작동하지 않습니다.
이것이 내가 chatList를 만든 방법입니다. 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)
}
})
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
}
})
이것은 메시지 타임 스탬프를 보내거나받을 때마다 데이터베이스의 사진입니다.

답변
2 AayushChaudhary Nov 16 2020 at 12:19
메시지의 타임 스탬프를 저장 한 다음 val chatListSenderReference = dbRef.child("ChatList").child(currentUserID).orderByChild("timestamp")
Tonnie Nov 22 2020 at 15:28
이것이 귀하의 경우에 효과가 있는지 확실하지 않지만 채팅 앱의 경우 메시지 목록이 있었고 목록을 정렬하는 것뿐입니다.
//sort method - takes a list to be sorted
private fun sortMessagesByDate(messages: MutableList<Message>) {
//sort messages by Date
messages.sortWith(compareBy { it.timestamp })
}
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()
}
그런 다음 ListView의 어댑터에서 Names List (contactsNames)를 전달합니다.
adapter =
ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, contactsNames)
그 후 특정 위치에서 이름을 클릭하면 앱은 클릭 한 연락처에 해당하는 UserObject를 가져 오는 DisplayMessage Fragment로 이동합니다.
//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]))
}
RecyclerView를 사용하여 연락처 이름을 표시 할 수도 있습니다.