by viewModels()
not resolving in Android Studio
I have the following dependencies in build.gradle(Module: GeoQuiz:app)
implementation 'androidx.activity:activity-ktx'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx'
I have found lots of conflicting info regarding the correct dependencies to use here when I googled for more info. Advice is welcome. Thanks.
1 Like
Make sure that you have synced your changes with Gradle. If Android Studio still can’t find the import after that, you can add it in manually. It is:
import androidx.activity.viewModels
Thanks, but I still cannot get this to work. Curious if others are encountering this same issue while working through the book.
What versions of those libraries are you using? The Gradle code that you provided at the beginning is missing the versions of each library. The full lines should be:
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
2+ years later I’m having the same problem though I suspect the nature of the problem has changed. Android Studio throws errors if we do as the book says which is the same as copying bryansillsbnr’s code from this thread. The solution is to: 1 wrap the code following ‘implementation’ with parenthesis and, 2 replace single quotes with double quotes.
implementation ‘androidx.activity:activity-ktx:1.4.0’
implementation ‘androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1’
becomes
implementation(“androidx.activity:activity-ktx:1.4.0”)
implementation(“androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1”)
This will work but I’m choosing to go with latest versions. According to https://developer.android.com/jetpack/androidx/releases/activity#kts and
জীবনচক্র | Jetpack | Android Developers
what follows is the most modern version
val lifecycle_version = “2.8.7”
val activity_version = “1.9.3”
implementation(“androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”)
implementation(“androidx.activity:activity-ktx:$activity_version”)
I recreated this for chapters 9 and 10 to build Criminal Intent and got weird errors. Deleted and re-entered same characters to make them go away, which (oddly) worked. There is an Android studio warning (‘use version catalogue instead’) that suggests an even better solution and it is formatted to look more like the rest of the implementations. Instead of
val lifecycle_version = "2.8.7"
val activity_version = "1.9.3"
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
implementation("androidx.activity:activity-ktx:$activity_version")
delete this code and try
implementation(libs.androidx.lifecycle.viewmodel.ktx)
implementation(libs.androidx.activity.ktx)
1 Like