Can't find ViewModelProviders class, only ViewModelProvider
Asked Answered
E

2

9

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

Existential answered 14/6, 2018 at 19:1 Comment(0)
P
15

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):

The contents of the extensions and viewmodel packages


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

Pipit answered 14/6, 2018 at 19:24 Comment(2)
Thanks. Here is some more detailed info about adding LifeCycle components into your project developer.android.com/topic/libraries/architecture/…Existential
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
S
4

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.

Salliesallow answered 9/11, 2019 at 13:51 Comment(1)
This should be the new right answer!Wanderjahr

© 2022 - 2024 — McMap. All rights reserved.