androidkotlinandroid-recyclerviewlistadapter

Why won't the Items in my RecyclerView update?


I have this ListAdapter:

ListAdapter<Item, RecyclerViewAdapter.ViewHolder>(object : DiffUtil.ItemCallback<Item>() {
        override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
            return oldItem.url == newItem.url
        }
    })

I'm trying to add more Items into the List when a button is clicked. But for some reason the ListAdapter won't notice, if there are new Items. Only when i go to another Fragment and then back it will update my recyclerview.

I've had this issue for a few weeks now and couldn't find any resources about it.

Edit:

This is how I add the Items after your answers

viewModel.addItem()
recyclerViewAdapter.notifyItemInserted(0)

And i observe the itemlist like this:

viewModel.itemList.observe(viewLifecycleOwner) { itemList ->
        (binding.recyclerView.adapter as? RecyclerViewAdapter)?.submitList(itemList)
}

Solution

  • Its because you are not notifying the adapter that the list has been refreshed or changed. You should use these after you update the list.notifyItemInserted(position) if you are adding only one value, or notifyItemRangeChanged(position, list.size).

    You can use notifyDataSetChanged() for the last resort if the whole list has been updated or nothing mentioned above works for you.