Search code examples
androidkotlinfragmentviewmodelmutablelivedata

Values are not added in MutableLiveData<MutableList<String>>()


I am using a fragment and viewmodel where the list values are not updated in the viemodel when the function is called from my fragment.

This is in my fragment

class SettingsFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val binding = FragmentSettingsBinding.inflate(inflater)
    val application = requireNotNull(this.activity).application
    val dataSource = UserInfoDatabase.getInstance(application).userInfoDao
    val viewModelFactory = SettingsViewModelFactory(dataSource, application)
    val settingsViewModel = ViewModelProvider(this, viewModelFactory).get(SettingsViewModel::class.java)
    binding.settingsViewModel = settingsViewModel
    binding.lifecycleOwner = this
    settingsViewModel.addValueToList("hello")
  }
}

This is from my ViewModel

class SettingsViewModel(val database: UserInfoDatabaseDao, application: Application): AndroidViewModel(application){
    private val _sectionList = MutableLiveData<MutableList<String>>()
    val sectionList: MutableLiveData<MutableList<String>>
        get() = _sectionList
    fun addValueToList(listValue: String){
    _sectionList.value?.add(listValue)
    }
 } 

When I try to print a toast message as _sectionList.value.toString() from my viewModel after trying to add values to the list, it shows null.

Thanks in advance for the help..


Solution

  • It's because you have not initialized the MutableList<>().

    class SettingsViewModel(val database: UserInfoDatabaseDao, application: Application): AndroidViewModel(application){
    
        private val _sectionList = MutableLiveData<MutableList<String>>()
    
        val sectionList: MutableLiveData<MutableList<String>>
            get() = _sectionList
    
        fun addValueToList(listValue: String){
    
           // In the following line: _sectionList.value is still null, so this will 
           // never call the add
            _sectionList.value?.add(listValue)
        }
     } 
    
    

    If you initialize with:

    init {
        _sectionList.value = mutableListOf<String>()
    }
    

    it should work hopefully.