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?
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.
To instantiate such basic viewmodel, create a ViewModelProvider with current activity/fragment reference and invoke get method with ViewModel's class.
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.
You need to use the support library
activity.
AppCompatActivity
or FragmentActivity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With