Cannot create instance of class ViewModel while using MVVM

后端 未结 1 1667
挽巷
挽巷 2020-12-22 09:31

I have created ViewModel class, and trying to create an instance of my ViewModel class using ViewModelProvider. At runtime, I\'m getting this error

相关标签:
1条回答
  • 2020-12-22 09:57

    As per the Lifecycle 2.2.0 release notes:

    ViewModelProviders.of() deprecation: ViewModelProviders.of() has been deprecated. You can pass a Fragment or FragmentActivity to the new ViewModelProvider(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'
    
    0 讨论(0)
提交回复
热议问题