I have created ViewModel
class, and trying to create an instance of my
ViewModel
class using ViewModelProvider. At runtime, I\'m getting this error
As per the Lifecycle 2.2.0 release notes:
ViewModelProviders.of()
deprecation:ViewModelProviders.of()
has been deprecated. You can pass aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality when using Fragment 1.2.0.
That last part is important, as otherwise new ViewModelProvider(this)
will only use the NewInstanceFactory
you see in the exception, which doesn't support AndroidViewModel
. AppCompat 1.1.0 only depends on Fragment 1.1.0, so you're not getting the support for the ViewModelProvider
constructor you're using.
Therefore, you should upgrade to Fragment 1.2.0 or higher (currently 1.2.4):
implementation 'androidx.fragment:fragment:1.2.4'