how to add data in ListAdapter?

3.8k Views Asked by At

In ListAdapter, how can I add data to existing list?

submitList() will only replace existing list with new one, maybe a method to updating data something like this

adapter.addNewItem(list)
2

There are 2 best solutions below

6
On BEST ANSWER

Instead of modifying data in ListAdapter, always update the datasource i.e list in your case and submit the updated list to ListAdapter

//assume you have this either in your view model or where ever it is
val dataList = ArrayList<String>()

fun updateData(newData: List<Data>){
    dataList.addAll(newData) // add new data to existing data
    adapter.submitList(dataList) //submit the data again
}
1
On

You can get the list from an adapter:

adapter.getCurrentList()

Then you need to create a copy, add a new item, and submit it to the adapter.