Android RecyclerView Adapter — Complete Guide
In this tutorial, you'll learn about Android RecyclerView Adapter. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You create a new <a href="/design-patterns/adapter/">Adapter</a> instance on every data change, call notifyDataSetChanged() for single-item updates, or mutate the list without notifying the Adapter.
Wrong Approach ❌
class MyAdapter : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private var items = mutableListOf<String>()
// Exposing mutable list directly
fun setItems(newItems: List<String>) {
items = newItems.toMutableList()
notifyDataSetChanged() // Massive overkill for single item change
}
fun addItem(item: String) {
items.add(item) // Mutating without notification
}
}
Output: Flickering list, IndexOutOfBoundsException, stale views.
Right Approach ✅
class MyAdapter : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private var items: List<String> = emptyList()
fun submitList(newItems: List<String>) {
val old = items
items = newItems
// Use DiffUtil instead of full refresh
DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun getOldListSize() = old.size
override fun getNewListSize() = newItems.size
override fun areItemsTheSame(i: Int, j: Int) = old[i] == newItems[j]
override fun areContentsTheSame(i: Int, j: Int) = old[i] == newItems[j]
}).dispatchUpdatesTo(this)
}
fun addItem(item: String) {
val newList = items + item
submitList(newList)
}
}
Output: Smooth, animated list updates with minimal view rebinds.
Prevention
- Always use
submitList()withDiffUtilorAsyncListDiffer. - Never mutate the backing list directly.
- Avoid calling
notifyDataSetChanged()— use targeted notifications. - Use
ListAdapter(built-in withAsyncListDiffer) for modern code.
Common Mistakes with recyclerview Adapter
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro