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);
this
is correct? If it's a Fragment you'll need to usegetActivity()
instead ofthis
iirc, and if you are in a listener or anonymous class you will have to doMainActivity@this
etc etc – BrevityboardViewModel = new ViewModelProvider(this).get(BoardViewModel.class)
, which is equivalent tomainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
which I already tried, but seems to be no suitable constructor. – Shaddock