I have a RecyclerView inside of a Fragment. I use Data Binding and Navigation Component. My problem is, when I go back to the previous fragment using the back arrow or just navigate back, and after that I open again the fragment, where I have the RecyclerView, the last item will be still there, but the list is totally empty.
I call this method when I close and open the fragment with the RecyclerView.
fun removeAllItems()
{
listOfItems.clear()
notifyItemRangeRemoved(0, listOfItems.lastIndex)
}
I have tried notifyDataSetChanged() also, but still I have the same issue.
Any idea why does it happen?
Thanks.
EDIT: Finally I could solve the problem. The onCreate() method:
private lateinit var listItemAdapter: ListItemAdapter
listItemAdapter = ListItemAdapter(context, mutableListOf<ListItem>())
Log.d(TAG, "Size_4: ${listItemAdapter.itemCount}")
listItemAdapter.removeAllItems()
binding.rvCreateNewListFourthItem.apply {
layoutManager = LinearLayoutManager(context)
adapter = listItemAdapter
}
Log.d(TAG, "Size_6: ${listItemAdapter.itemCount}")
Results: Size_4: 0 Results: Size_6: 0
After thse lines I have only 2 setOnClickListeners, which opens 2 other dialogs.
override fun onResume()
{
super.onResume()
Log.d(TAG, "Size_3: ${listItemAdapter.itemCount}")
listItemAdapter.removeAllItems()
Log.d(TAG, "Size_5: ${listItemAdapter.itemCount}")
}
Results: Size_3: 1 Results: Size_5: 0
The solution was to call the removeAllItems() method on the adapter. When the fragment reached the onResume() method, the list contained the last item from the last session.