Search code examples
androidandroid-layoutandroid-fragmentsandroid-viewmodel

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?


Solution

  • You need to use the support library activity.

    AppCompatActivity or FragmentActivity