Search code examples
javaandroidandroid-fragmentsviewmodelandroid-viewmodel

ViewModelProvider Fragment instantiate model


I have a model which is started on my "MainActivity.java" which is called like this:

//MainActivity.java (public class MainActivity extends AppCompatActivity {...)
...
private ModelName mViewModel;
...
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewModel = new ViewModelProvider(this).get(ModelName.class);
}
...

As of now, I was using this approximation in each of my fragments to instantiate the same model and be able to interact with the variables within it:

//FragmentClass.java (public class F1_Start_Acquisition extends Fragment {...)
...
private ModelName mViewModel;
...
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.f1__test__fragment, container, false);
        mViewModel = ViewModelProviders.of((FragmentActivity) 
              getActivity()).get(ModelName .class);
}

The ViewModelProviders.of got deprecated, and I see everywhere that it should be replaced with new ViewModelProvider(this).get(ModelName.class);, but I don't want to create a new instance of the model, I just want to get the existing instance already created, and I have tried many approaches which did not work...

Could someone please tell me how to access the already existing instance of the model from the Fragment.java initialisation class?


Solution

  • mViewModel = new ViewModelProvider(requireActivity()).get(ModelName.class);
    

    When you use the above code. Notice that fragment retrieves the activity that contains them. In this way, it will not instantiate a new object instead it will return the same as attached to the activity.

    You can check by using the Logcat. Just use mViewmodel.toString() in the activity and fragment.

    I hope you get it.