Search code examples
androidandroid-fragmentsandroid-livedataandroid-architecture-componentsandroid-viewmodel

Android ViewModel doesn't survive fragment change


I've been trying to share information between fragments using viewmodel's and livedata's.

But when I change from first fragment to another it seems that my viewmodel is reinitialized, making me lose all my previously stored data.

I get both times my viewmodel the same way in my fragments :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    interventionViewModel = ViewModelProviders.of(this).get(InterventionsViewModel.class);

}

And this is how I replace my framgents in my activity (I guess the problem must come from the fragments lifecycles but I can't figure out where is the error :/)

public void showFragment(Fragment fragment) {

    String TAG = fragment.getClass().getSimpleName();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment, TAG);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commitAllowingStateLoss();
}

public void backstackFragment() {
    Log.d("Stack count", getSupportFragmentManager().getBackStackEntryCount() + "");
    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        finish();
    }
    getSupportFragmentManager().popBackStack();
    removeCurrentFragment();
}

private void removeCurrentFragment() {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    Fragment currentFrag = getSupportFragmentManager()
            .findFragmentById(R.id.fragment_container);

    if (currentFrag != null) {
        transaction.remove(currentFrag);
    }
    transaction.commitAllowingStateLoss();
}

When I need a fragment I call backStackFragment() to remove current fragment then I call showFragment(MyFragment.newInstance());

The fragment are the ones generated by AndroidStudio

Thanks for your help,

Cordially, Matthieu


Solution

  • Try binding to the activity instead of the current fragment.

    interventionViewModel = ViewModelProviders.of(activity).get(InterventionsViewModel.class);