I have a fragment that starts a second activity upon some button click. This second activity is where the user makes some selections. I want to update a TextView in the fragment based on the user's selections from the second activity. I am using a ViewModelFactory in order to get access to the same ViewModel in the Fragment from within the second Activity (from the solution from Amir Raza found at: Android LiveData - how to reuse the same ViewModel on different activities?)
But the TextView is not being updated.
I found answers here:
Update textView in Fragment from Activity
But this answer does not use LiveData.
Fragment:
class CreatePlanFragment : Fragment()
{
private lateinit var vmCreatePlan: NameViewModel
...
vmCreatePlan = ViewModelProviders.of(this, ViewModelFactory.getInstance()).get(NameViewModel::class.java)
val tvStartReference: TextView = view.findViewById(R.id.create_plan_start_ref)
vmCreatePlan.referenceStart.observe(this, Observer {
tvStartReference.text = it
})
}
Second Activity:
class ActivitySelectReference : AppCompatActivity()
{
private lateinit var vmCreatePlan: NameViewModel
...
vmCreatePlan = ViewModelProviders.of(this, ViewModelFactory.getInstance()).get(NameViewModel::class.java)
reference_button_ok.setOnClickListener {
vmCreatePlan.referenceStart.postValue("New Label")
//vmCreatePlan.referenceStart.value ="New Label"
finish()
}
}
ViewModel:
class NameViewModel : ViewModel()
{
val referenceStart: MutableLiveData<String> = MutableLiveData<String>().apply {
value = "Old Label"
}
companion object
{
private var instance: NameViewModel? = null
fun getInstance() = instance ?: synchronized(NameViewModel::class.java) {
instance ?: NameViewModel().also { instance = it }
}
}
}
ViewModelFactory:
class ViewModelFactory : ViewModelProvider.NewInstanceFactory()
{
override fun <T : ViewModel?> create(modelClass: Class<T>) = with(modelClass) {
when
{
isAssignableFrom(NameViewModel::class.java) -> NameViewModel.getInstance()
else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
}
} as T
companion object
{
private var instance: ViewModelFactory? = null
fun getInstance() = instance ?: synchronized(ViewModelFactory::class.java) {
instance ?: ViewModelFactory().also { instance = it }
}
}
}