问题
I am trying to sort a list of User Objects by the order in which User IDs appear in the MessageList Array. The MessageList consists of ID's of people a user is chatting with (ordered by time - using sortwith), which is then to be sent to a User Adapter as a list of Users in the same order as the message list. This is so that username, profile image and other details can be displayed... I have learnt a datasnapshot of the Users from firebase provides as is order and hence needs to be ordered again..
I have tried to sort the User Array List basis the MessageList but it has issues with id access (asking me to make it public) and that the final output is no longer a list of users. How would you proceed to showcase a timestamp ordered MessageList?
Users Data Class
class Users {
private var uid: String = ""}
MessageList Data Class
class MessageList {
private var id: String = ""
private var chattimeStmp: Long = 0}
Function that creates the User List based on the MessagesList
private var userMsgAdapter: UserMsgAdapter? = null
private var mUsers: List<Users>? = null
private var usersMsgList: List<MessageList>? = null
private var firebaseUser : FirebaseUser? = null
lateinit var recycler_view_msgList : RecyclerView
private fun retrieveMessageList()
{
mUsers = ArrayList()
val ref = FirebaseDatabase.getInstance().reference.child("Users")
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
(mUsers as ArrayList).clear()
//sorting MessageList based on timestamp
usersMsgList?.sortedBy { it.getChattimeStmp() }
for (dataSnapshot in p0.children) {
val user = dataSnapshot.getValue(Users::class.java)
for (eachMessageList in usersMsgList!!) {
if (eachMessageList.getId()
.equals(user!!.getUID()) && !firebaseUser?.uid.equals(
eachMessageList.getId()
)
) {
(mUsers as ArrayList).add(user)
}
}
}
//Creating a map and sorting list based on the other
val orderById = usersMsgList!!.withIndex().associate { it.value to it.index }
val mSortedUsers = (mUsers as ArrayList<Users>).sortedBy { orderById[it.getUID()] }
userMsgAdapter = UserMsgAdapter(context!!, mUsers as ArrayList<Users>, true)
userMsgAdapter!!.notifyDataSetChanged()
recycler_view_msgList.adapter = userMsgAdapter
}
override fun onCancelled(p0: DatabaseError) {
}
}
)
}
回答1:
The best solution in this case is to not sort the User Objects based on the order they appear in the Messagelist but directly call the recycler view for each object in the MessageList and get user details in the adapter.
来源:https://stackoverflow.com/questions/64861151/ordering-users-list-based-on-messagelist-kotlin-android