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

3

9

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 ?

Amaliaamalie answered 10/3, 2018 at 14:26 Comment(0)
T
13

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

Turtleback answered 10/3, 2018 at 14:59 Comment(4)
To clarify - it'll work if Support Fragments are usedResurrectionism
Yes, if getActivity() is returning an android.app.Activity instance, then you are using native fragments. You need to use the backport of fragments. Partly, that is so you can use ViewModelProviders. Partly, that is because the native fragments are deprecated in Android P.Turtleback
So, this means I'll have to change my Activity, which displays the two Fragments from "extends Activity" to "extends FramgmentActivity" ? If I understood this correctly.Amaliaamalie
@Tobias420d: Yes, and change your fragments to use the Support Library edition (android.support.v4.app.Fragment) to match. That in turn will require you to use getSupportFragmentManager() instead of getFragmentManager().Turtleback
B
1

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!

Balsamic answered 3/5, 2019 at 14:13 Comment(0)
W
0

Just cast getActivity() to specific activity. It works for me. For example:

model = ViewModelProviders.of((MainActivity)getActivity()).get(UserAccountViewModel.class);
Waterhouse answered 19/4, 2020 at 18:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.