Search code examples
androidandroid-viewmodel

How do I get a ViewModel without ViewModelProviders class?


Relating to the past question How to get a ViewModel?, and examples I've found, it does not solve my case. I don't have permission to comment there, so I have to ask again. I don't have the ViewModelProviders class which I would like to use the "of" method as in all the examples and documentation I've found, like

model = ViewModelProviders.of(this).get(Something.class);

In Android Studio, I do not find "android.arch.lifecycle:extensions" to add as a dependency. It says "nothing to show" when I search. I am at API 27. So, trying to use the non-deprecated elements, I have this in the Fragment:

public class EventDetailsFragment extends Fragment
{
EventViewModel viewModel;

@Override
public void onActivityCreated (Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication());
    // HERE IS THE ISSUE: Seems not good practice to have to create a new ViewModelProvider every time this Fragment is created. 
    // Perhaps I should just create a singleton ViewModelProvider in the Activity or Application, 
    // so here could call getActivity().getViewModelProvider(this, factory).
    ViewModelProvider viewModelProvider = new ViewModelProvider(this, factory);
    viewModel = viewModelProvider.get(EventViewModel.class);
...
}

What should I do?


Solution

  • Open app/build.gradle, find the dependencies block and add the lifecycle dependency manually to the list:

    dependencies {
        implementation 'android.arch.lifecycle:extensions:1.1.1'
    
        // ... 
    }
    

    Sync the project and you should be able to get an instance of ViewModel afterwards.