I am trying to create lifecycle-aware view models. But I can't find ViewModelProviders
class in my Android project, only ViewModelProvider
. There seems to be no android.arch.lifecycle.ViewModelProviders
package for me to import as well. What's happening
Can't find ViewModelProviders class, only ViewModelProvider
You probably have this dependency included in your project:
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version"
That contains ViewModelProvider
(and just 4 other classes), but ViewModelProviders
is in a different package:
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
Here are the contents of these packages for reference (as of version 1.1.1):
For the record, you can find this out yourself by looking up the docs for the ViewModelProviders
class, where it says up top:
added in version 1.1.0
belongs to Maven artifact android.arch.lifecycle:extensions:1.1.1
With API 29, the architecture components have been moved to the
androidx.*
namespace. You should therefore use implementation "androidx.lifecycle:lifecycle-extensions:$lifecycleVersion"
and implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycleVersion"
. At the time of writing this, using $lifecycleVersion='2.0.0-rc1'
will work. Note that the libs are backwards compatible, so this will also work for apps with API compatibility < 29. –
Wanonah Also, just for future reference.
ViewModelProviders
class is now deprecated.
According to Android Developers Documentation: ViewModelProviders
This class is deprecated. Use the constructors for ViewModelProvider directly.
This should be the new right answer! –
Wanderjahr
© 2022 - 2024 — McMap. All rights reserved.
LifeCycle
components into your project developer.android.com/topic/libraries/architecture/… – Existential