0

I have a MainViewModelwith the code:

private val locationList: MutableLiveData<ArrayList<Location>> = MutableLiveData()
fun getLocationList(): MutableLiveData<ArrayList<Location>> = locationList

and a fragment where I am trying to add values to the arraylist, but I don't know how:

mainViewModel.getLocationList.value = arrayListof(location) //creates always a new list

Maybe someone can help me. Thank you

zeppal
  • 181
  • 7

1 Answers1

3
mainViewModel.getLocationList.value?.add(newLocation)
mainViewModel.getLocationList.value = mainViewModel.getLocationList.value // notify observers
Puelloc
  • 101
  • 3
  • I have tried it, but it doesn't work for me. For example I want the value with `Log.d("location",mainViewModel.getLocationList.value.toString())`, I only get `null` as response. – zeppal Jun 29 '22 at 14:36
  • Get null before you post a initial value or always null? – Puelloc Jun 29 '22 at 15:05
  • My code looks like this: ```mainViewModel.getLocationList.value?.add(newLocation) mainViewModel.getLocationList.value = mainViewModel.getLocationList.value Log.d("location",mainViewModel.getLocationList.value.toString()) ``` – zeppal Jun 29 '22 at 15:08
  • You should assign a empty list first, or assign a list contains newLocation when the value is null. – Puelloc Jun 29 '22 at 15:15
  • Maybe you can get more information in this question https://stackoverflow.com/questions/47941537/notify-observer-when-item-is-added-to-list-of-livedata – Puelloc Jun 29 '22 at 15:23