0

I am new to android and working on an application where i have use shared ViewModel across fragments there are a lot of help for kotlin but for java there is nothing. Please guide me if possible.?

Vivek M Fauzdar
  • 127
  • 1
  • 13

1 Answers1

0

Follow the documentation, and remember to use the same ViewModelStoreOwner, like this:

public class SharedViewModel extends ViewModel {

}

public class FragmentA extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //pass the host Activity
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    }
}

public class FragmentB extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         //pass the host Activity
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    }
}