ViewModel return clear object when i try to get data from it


I'm trying to use ViewModel, for saving data to share between Fragments. That is it:

class AnimalViewModel : ViewModel() {
    private var data = MutableLiveData<AnimalWithHints>()

    fun setData(animalData: AnimalWithHints) {
        data.value = animalData

    fun getData(): LiveData<AnimalWithHints> {
        if (data.value == null) {
            data.value = AnimalWithHints()
        return data

So I've filled non-null object (checked it) and I write before transaction:


I see "Saved?" when it happens, so I think save working good. I logged some field of AnimalWithHints, and I saw it was correct.

Then I try to get my object:

val animalWithHints = ViewModelProviders.of(this).get(

And I see "Null?". And it's true, data.value is rly new empty AnimalWithHints object.

Strange thing is I have only two lines of code, using ViewModel. I only save and get object, there is no place when I can clear it or modify somehow.

I need you help to understand what's wrong.

Jeel Vankhede

When you want to share data between your Fragments that are in same Activity, you'll need to create instance of ViewModel with context to Activity.

Below syntax provides you instance of ViewModel that is at Fragment level only (You can share it at Fragment itself with some child fragments inside of that Frament):

ViewModelProviders.of([email protected])[] // This will give you view model at fragment level

While passing Activity object to your ViewModelProvider inside your Fragment gives you ViewModel at Activity level. Hence You're having multiple Fragments inside same Activity meaning context of Activity is same gives your same ViewModel object at both Fragments.

So for sharing ViewModel between fragments, use below syntax :

ViewModelProviders.of(activity)[] // This will provide you shared view model across multiple fragments.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment


TOP Ranking