I get this ArrayList
named items containing several Data class
in Adapter
.
[DiaryCard(writeTime=2023-01-04, name=신혜정, stepCount=0, mood=2131230894, diary=안녕하세요),
DiaryCard(writeTime=2023-01-04, name=신혜정, stepCount=11, mood=2131230894, diary=hi),
DiaryCard(writeTime=2023-01-04, name=신태건, stepCount=0, mood=2131230898, diary=대단히 반갑습니다)]
I want to sort them by key 'writeTime' before I bind this data to View in ViewHolder
.
var items = items
var sortItems = items.sortedBy { it.writeTime }
inner class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var userWriteTime: TextView = itemView.findViewById(R.id.userWriteTime)
var userNameView: TextView = itemView.findViewById<TextView>(R.id.userName)
var userStepCountView: TextView = itemView.findViewById<TextView>(R.id.userStepCount)
var userMoodView: ImageView = itemView.findViewById<ImageView>(R.id.userMood)
var userDiaryView: TextView = itemView.findViewById<TextView>(R.id.userDiary)
fun bind(position: Int) {
Log.d("결과아", "items: $items")
Log.d("결과아", "sortItems: $sortItems")
userWriteTime.text = sortItems[position].writeTime
userNameView.text = sortItems[position].name
userStepCountView.text = "${sortItems[position].stepCount}보"
userMoodView.setImageResource((sortItems[position].mood ?: 2131230873).toInt())
userDiaryView.text = sortItems[position].diary
}
}
So I create var sortItems which sort items by using sortedBy
.
And I link this sortItems var to function bind instead of items.
But it won't work.
When I print items and sortItems, items show above ArrayList containing 3 DiaryCard Data class.
But sortItems show empty ListArray, [].
So How can I sort ArrayList by one component of DataClass?
Plus, my writeTime is String value coming from LocalDate.now()
.
How can I sort them LocalDate.now() in order for the most recent data to come first?
I use Kotlin
, please help me with detail code.
Thank you!
CodePudding user response:
items.sortByDescending { item -> item.writeTime }
The method sortByDescending mutates the original list sorting it descending using the size of the list as selector to make the comparison between elements.
CodePudding user response:
You can use sortByDescending
to get recents one first. Documentation
var sortItems = items.sortByDescending { it.writeTime }