To do this challenge I had to create a class for the DiffUtil functions, I called it MyDiffUtil.
It aims to compare the new and old list of crimes once a user change anything…
package com.bignerdranch.android.recyclerviewlistadapter
import androidx.recyclerview.widget.DiffUtil
class MyDiffUtil(
private val oldList: List<Crime>,
private val newList: List<Crime>
): DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return when{
oldList[oldItemPosition].id != newList[newItemPosition].id -> false
oldList[oldItemPosition].date != newList[newItemPosition].date -> false
oldList[oldItemPosition].isSolved != newList[newItemPosition].isSolved -> false
oldList[oldItemPosition].title != newList[newItemPosition].title -> false
else -> true
}
}
}
Then inside the adapter I added setData function to run the DiffUtil Class
private inner class CrimeAdapter(var crimes: List<Crime>)
: RecyclerView.Adapter<CrimeHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
: CrimeHolder {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.list_item_crime, parent, false)
return CrimeHolder(view)
}
override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
val crime = crimes[position]
holder.bind(crime)
}
override fun getItemCount() = crimes.size
/**
* Implementing List Adapter after creating the MyDiffUtil.kt Class
*/
fun setData(newCrimeList : List<Crime>){
val diffUtil = MyDiffUtil(crimes, newCrimeList)
val diffResult = DiffUtil.calculateDiff(diffUtil)
crimes = newCrimeList
diffResult.dispatchUpdatesTo(this)
}
}
after that i submitted the data into the UpdateUI function
private fun updateUI(crimes: List<Crime>) {
adapter = CrimeAdapter(crimes)
crimeRecyclerView.adapter = adapter
/**
* Adding logic to run the ListAdapter
*/
adapter.setData(crimes)
}
List adapter can be implemented in several ways…
you can add the logic of DiffUtil within the Crime.kt data class itself also…
but this one i found the easier… in case anyone finds any problem in it please inform