Unresolved reference: viewModels() [duplicate]
Asked Answered
B

1

6

I just started an Android App and I want to use ViewModel. I looked into documentation and I put all the dependencies from Lifecycle but when i try to instantiate a view model like this viewMyViewModel by viewModels() i get this error 'Unresolved reference: viewModels()'.

These are the dependencies:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    def lifecycle_version = "2.2.0"
    def arch_version = "2.1.0"

    implementation "android.arch.lifecycle:extensions:1.1.1"
    kapt "android.arch.lifecycle:compiler:1.1.1"

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

    implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"
    testImplementation "androidx.arch.core:core-testing:$arch_version"

}
Boast answered 29/4, 2020 at 9:3 Comment(1)
I think this question deserves to be re-opened. Although the subject is similar to the other one but the actual problem faced by him is different.Shuping
S
2

Include this in your dependency,

implementation "android.arch.lifecycle:extensions:1.1.1"

then, add apply plugin: 'kotlin-kapt' in build.gradle

then add,

kapt "android.arch.lifecycle:compiler:1.1.1"

Replace other annotationProcessor with kapt

See if it works or not, if not, then go to

file -> invalidate cache and restart

Sourdine answered 29/4, 2020 at 9:12 Comment(2)
Still doesn't work. I added the dependencies, maybe it helpsBoast
try to rebuild the projectSourdine

© 2022 - 2024 — McMap. All rights reserved.