I have a recyclerview inside a fragment that displays a mutable list of tasks that each have a title and description, wrapped in mutable live data.
private val _tasks = MutableLiveData<MutableList<Task>>()
To add those items, i implemented a bottom sheet dialog fragment with text edits for both values.
When i add a task item without specifying the index the recyclerview updates correctly :
_tasks.value!!.add(Task(taskEditText,descriptionEditText))
However, when i specify i want the new task item at index 0 and i add multiple task items, the recyclerview displays the first task i added over and over.
Things i've tried:
Using notifyDataSetChanged inside the adapter works and updates the recyclerview correctly, however i tried adding it to my add task button inside my bottom sheet dialog and it does nothing.
I tried adding the items to a temporary list and then setting it to _tasks.value but the same thing happened, only updates when i dont specify the index.
Here are relevant files :
AddTaskFragment (Bottom Sheet Dialog) :
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = viewLifecycleOwner
// if the textfields are not empty, adds the task and leaves the dialog
binding.buttonAdd.setOnClickListener{
if (binding.addTaskEditText.text!!.isNotEmpty() && binding.addDescriptionEditText.text!!.isNotEmpty()) {
viewModel.addTask(binding.addTaskEditText.text.toString(), binding.addDescriptionEditText.text.toString())
dismiss()
}
}
}
addTask function inside viewmodel :
fun addTask(taskEditText : String, descriptionEditText : String) {
_tasks.value!!.add(0,Task(taskEditText,descriptionEditText))
}
Adapter:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val task = viewModel.tasks.value!![position]
holder.itemTitle.text = task.text
holder.itemDescription.text = task.description
holder.textViewOptions.setOnClickListener {
onMenuClick(position, holder, task)
}
}
Thanks in advance and i hope you pros can help me
viewModel.tasks.observe(viewLifecycleOwner, Observer {
adapter.notifyDataSetChanged()
})
Try it.