I am new to the mvvm pattern. I created a ViewModel for the main activity. Now I want to get an instance of the ViewModel in the main activity.
Most Tutorials and answers here on Stackoverflow suggest using ViewModelProviders.of(...
, but this is depreceated.
So according to this question on stackoverflow: ViewModelProviders is deprecated in 1.1.0 main activity in onCreate, I do the following (and I could swear I already had it running): mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
However, I am getting an error telling me, that no suitable constructor has been found.
error: no suitable constructor found for ViewModelProvider(MainActivity)
Alternatively to make absolutely clear, that the MainActivity shall be the ViewModelStoreOwner, I created a variable ViewModelStoreOwner vmso = this;
and put that variable into the constructor like so: mainActivityViewModel = new ViewModelProvider(vmso).get(MainActivityViewModel.class);
onCreate(savedInstanceState); setContentView(R. layout. main); activity = this; // Create an instance of Camera mCamera = getCameraInstance(); // Create our Preview view and set it as the content of our activity. mPreview = new CameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.
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.
In order to use ViewModel, add a dependency on androidx. lifecycle's lifecycle-viewmodel-ktx library in your module's build. gradle file and sync the changes. For every Activity or Fragment, whose data you want to preserve using ViewModel, creating a separate class is highly recommended.
You should update your gradle file to:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
And due to this change you can pass Activity to the constructor you mentioned:
mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
Using Fragment-ktx libr in your app you can get viewModel as below
implementation 'androidx.fragment:fragment-ktx:1.1.0'
// get ViewModel in Activity or Fragment as
private val viewModel: MainActivityViewModel by viewModels()
// If you want to get same instance of ViewModel in ChildFragment as
private val viewModel: MainActivityViewModel by viewModels( ownerProducer = { requireParentFragment() } )
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