-1

I have main Fragment and DialogFragment. In Start i go in dialogFragment with list of city and get one for save in LiveData

listOfCities.setOnItemClickListener { parent, view, position, id ->
            homeViewModel.selectCityTo((listOfCities.getItemAtPosition(position) as HashMap<String, String>).getValue("name"))
            Log.e("Search", homeViewModel.cityTo.value)
}

I checked through Logcat and its work. But when i returned to main Fragment, Livedata is empty. TextView(cityTo) does not change

 homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val cityFrom = root.findViewById<TextView>(R.id.cityFrom)
        val cityTo = root.findViewById<TextView>(R.id.cityTo)
        homeViewModel.cityFrom.observe(viewLifecycleOwner, Observer {
            cityFrom.text = it
        })
        homeViewModel.cityTo.observe(viewLifecycleOwner, Observer {
            cityTo.text = it
        })

ViewModel

class HomeViewModel : ViewModel() {

    private val _cityFrom = MutableLiveData<String>()
    private val _cityTo = MutableLiveData<String>()

    val cityFrom: LiveData<String> = _cityFrom
    val cityTo: LiveData<String> = _cityTo

    fun selectCityTo(to: String){
        _cityTo.value = to
        Log.e("hViewModel", "${cityTo.value}")

    }
    fun selectCityFrom(from: String){
        _cityFrom.value = from
    }
}
MXF
  • 79
  • 1
  • 9
  • 1
    May I suggest using `by viewModels()` and `by activityViewModels` from ktx extensions? See https://developer.android.com/topic/libraries/architecture/viewmodel – Joozd Jan 12 '21 at 21:58

1 Answers1

2

You should pass the activity to the ViewModelProvider (in both fragments where you create the viewmodel):

ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)

If you pass the Fragment, you will get a different ViewModel in each Fragment.

Fernandez
  • 36
  • 2