Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel cannot be instantiated in an Activity

I am trying to instantiate one ViewModel to use across all of my Activity(s).

public class LaunchActivity extends Activity {
    private Controller control;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_launch);
         control = ViewModelProviders.of(this).get(Controller.class);
    }
}

but I got an error at control = ViewModelProviders.of(this) <-- stating that it cannot resolve of(this), but based on the example here by Android Developer on Implementing ViewModel; a class that extends ViewModel should be able to be instantiated on Activity, am I right?

If what I am doing is wrong, how should I instantiate a ViewModel object for my Activity(s)? Do I have to create n number of Activity(s) with Fragment(s) since ViewModelProviders.of() only works with Fragment?

like image 850
dude Avatar asked Dec 07 '17 15:12

dude


People also ask

Can an activity have a ViewModel?

In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.

How do you instantiate a ViewModel in Java?

To instantiate such basic viewmodel, create a ViewModelProvider with current activity/fragment reference and invoke get method with ViewModel's class.

Is ViewModel destroyed when activity destroy?

The lifecycle of a ViewModel The ViewModel remains in memory until the ViewModelStoreOwner it's scoped to goes away permanently: In the case of an activity, when it finishes. In the case of a fragment, when it's detached.


1 Answers

You need to use the support library activity.

AppCompatActivity or FragmentActivity

like image 77
elmorabea Avatar answered Sep 28 '22 13:09

elmorabea