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.?
Asked
Active
Viewed 337 times
0
-
Did you read [the documentation](https://developer.android.com/topic/libraries/architecture/viewmodel#sharing) and its Java example? – CommonsWare Jul 27 '22 at 12:40
-
Also [fragment documentation](https://developer.android.com/guide/fragments/communicate). – Kozmotronik Jul 27 '22 at 12:43
-
@CommonsWare yes i have read them but did not get it properly.. – Vivek M Fauzdar Jul 27 '22 at 13:07
-
ViewModelProviders has been deprecated - see [this discussion](https://stackoverflow.com/questions/53903762/viewmodelproviders-is-deprecated-in-1-1-0) – oceanodroma Nov 06 '22 at 12:09
1 Answers
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);
}
}

Bingo Zhang
- 1
- 3