Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModelProviders.of(getActivity()) "Cannot resolve method of(android.app.Activity)"

I'm currently trying to share data between my two fragments with the help of a view model Android ViewModels.

In the this article they use "ViewModelProviders.of(getActivity()).get(SharedViewModel.class);" in the Fragment to get the model.

My Problem is, that when I write the exact same line into my fragment, I get a "Cannot resolve method of(android.app.Activity)" error

model = ViewModelProviders.of(getActivity()).get(UserAccountViewModel.class);

Can some one help me with this ?

like image 449
Tobias420d Avatar asked Mar 10 '18 14:03

Tobias420d


2 Answers

ViewModelProviders requires that you use FragmentActivity (or something derived from it), not Activity, as the base class of your activities.

like image 178
CommonsWare Avatar answered Nov 18 '22 11:11

CommonsWare


You might also get a similiar error like Cannot resolve method 'of(android.support.v4.app.FragmentActivity)' from ViewModelProviders.of(getActivity()) if you were trying to import androidx in your gradle file when your app is still using android.support.v4

This is different to the question being asked but is in the same ballpark and ranks first in Google when I had the problem, so I'm posting it!

like image 32
georgiecasey Avatar answered Nov 18 '22 13:11

georgiecasey