Home > Enterprise >  Couldn't find `activityViewModels()` Hilt Android
Couldn't find `activityViewModels()` Hilt Android

Time:12-03

I'm using Hilt and MVVM at my project and I want to get an viewModel from activityViewModel to use same in 2 activites. But my Android Studio says Unresolved Reference.

My app build.gradle is like this:

plugins {
        id 'com.android.application'
        id 'kotlin-android'
        id 'kotlin-kapt'
        id 'dagger.hilt.android.plugin'
    }

. . .

dependencies {

. .  .

implementation "com.google.dagger:hilt-android:2.38.1"
kapt "com.google.dagger:hilt-android-compiler:2.38.1"

implementation 'androidx.hilt:hilt-navigation-fragment:1.0.0'

implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
kapt 'androidx.hilt:hilt-compiler:1.0.0'
. . .
}

My project build.gradle file is like this:

classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'

I'm trying to get ViewModel like this:

private val viewModel: SelectWifiViewModel by activityViewModels()

CodePudding user response:

activityViewModels is used to get a reference to the ViewModel scoped to its Activity inside a fragment. If you want to used same ViewModel in both the activities, I would suggest you to switch to Fragments instead.

CodePudding user response:

Try adding this dependency:

dependencies {
    def fragment_version = "1.4.0"

    // Java language implementation
    implementation "androidx.fragment:fragment:$fragment_version"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}

Source: https://developer.android.com/jetpack/androidx/releases/fragment

CodePudding user response:

activityViewModels() has nothing to do with Hilt

you need a different dependency for that. It is in

implementation "androidx.fragment:fragment-ktx:1.4.0"
  • Related