CodexBloom - Programming Q&A Platform

Unexpected NullPointerException in RecyclerView Adapter on Android 14 with Data Binding

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-20
android recyclerview databinding kotlin

This might be a silly question, but I'm stuck on something that should probably be simple... I'm encountering a `NullPointerException` in my `RecyclerView` adapter when using data binding in Android 14. The error occurs during the binding process of the views, specifically when trying to access an item in the list. The stack trace points to the line where I call `binding.setVariable(BR.item, item)` in the `onBindViewHolder` method. My adapter looks like this: ```kotlin class MyAdapter(private val items: List<MyItem>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = ItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(binding) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val item = items[position] holder.bind(item) } override fun getItemCount() = items.size inner class MyViewHolder(private val binding: ItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: MyItem) { binding.setVariable(BR.item, item) binding.executePendingBindings() } } } ``` The `MyItem` class is a simple data class with a few properties. I've checked that the `items` list is populated correctly before passing it to the adapter, but I still get the exception when scrolling the `RecyclerView`. The error message I see is: ``` java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.myapp.databinding.ItemLayoutBinding.setVariable(int, java.lang.Object)' on a null object reference ``` I've tried adding null checks around the `binding` variable, but that only leads to skipped bindings, and the UI doesn't update as expected. I am using the latest version of Android Studio with Gradle 8.0. Any insights on why this might be happening or how to fix it would be greatly appreciated. Is there something I might be overlooking in the data binding setup? Is there a better approach? This is part of a larger application I'm building. What's the best practice here?