Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AndroidViewModel does not preserve state between Fragment switch

I was under the impression, that a ViewModel would preserve state and data between Fragment switches, as long as they belong to the same Activity. That does not seem to be the case.

My ViewModel:

public class MainViewModel extends AndroidViewModel {

    public MainViewModel(@NonNull Application application) {
        super(application);

        Log.d("MainViewModel","constructor called");
    }
}

Access in a fragment:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);

I noticed that the constructor is called every time I request the ViewModel. I thought that the purpose of the ViewModel was to stay alive all this time and could be used to preserve some state between fragments. Am I doing this wrong? Was my expectation wrong? How can I preserve state between fragments?

>Solution :

The issue is that you are using a ViewModelProvider that is scoped to the fragment instance rather than the parent activity instance. Replace new ViewModelProvider(this) with new ViewModelProvider(requireActivity()).

More info available in the documentation: https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-apis#vm-api-any-owner

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading