I am in the process of improving my app stability and performance, but right now I am stuck at a warning from Android Studio. Please consider the following Adapter class:
private class CoinsAdapter(private val fragment: CoinFragment, private val coins: List<Coin>): RecyclerView.Adapter<CoinsAdapter.ViewHolder>(), Filterable {
private val filter = ArrayList(coins)
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
val binding = ItemCoinBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val coin = filter[position]
holder.binding.coinImage.setImageResource(coin.image)
holder.binding.coinText.text = builder.toString()
}
override fun getItemCount() = filter.size
override fun getFilter() = object : Filter() {
override fun performFiltering(constraint: CharSequence): FilterResults {
if (constraint.length < 2) return fetchResults(coins)
val pattern = constraint.toString().lowercase().trim()
val filter = arrayListOf<Coin>()
for (coin in coins) if (coin.name.lowercase().contains(pattern)) filter.add(coin)
return fetchResults(filter)
}
private fun fetchResults(coins: List<Coin>): FilterResults {
val results = FilterResults()
results.values = coins
return results
}
override fun publishResults(constraint: CharSequence, results: FilterResults) {
filter.clear()
filter.addAll(results.values as List<Coin>)
notifyDataSetChanged()
}
}
private inner class ViewHolder(val binding: ItemCoinBinding) : RecyclerView.ViewHolder(binding.root)
}
The adapter and filter work perfectly but notice the publishResults
function. Android Studio is warning that regarding the notifyDataSetChanged
.
It will always be more efficient to use more specific change events if you can. Rely on notifyDataSetChanged as a last resort.
However, I am clueless on how to use the notifyDataSetChanged
in this instance (with a filter). What would be the right method and how to use it in this case?