'by viewModels()' Kotlin property delegate unresolved reference

Viewed 22020

I'm trying to implement viewmodel with kotlin. First I added the needed dependecies:

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
// Annotation processor
kapt "androidx.lifecycle:lifecycle-compiler:2.2.0"

Then I created a simple viewmodel:

class MyViewModel: ViewModel() {
    val greeting = "Hello World"
}

But when I tried to access the view model from the activity with kotlin property delegate:

val model by viewModels<MyViewModel>()

The compiler does not resolve viewModels. I don't know what the problem is. Did I miss something?

6 Answers

For me the solution above this not work.

I needed to import :

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'

For me the solution above this not work.

Add this dependency: :

implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'

Add This dependency :

 implementation "androidx.lifecycle:lifecycleviewmodel:2.2.0"

Resolved this error, using below dependency in module-level build.gradle

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'

OR

implementation 'androidx.lifecycle:lifecycle-extensions-ktx:2.2.0'
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.3.6'

I have also added below dependency to implement ViewModel in Kotlin

implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'

My module-level build.gradle start as per below

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

In my case, I was just using the wrong type of Activity. I had an android.app.Activity instead of an androidx.appcompat.app.AppCompatActivity.viewModels() is only available in the latter.

For me, I was having the following dependencies:

implementation 'androidx.activity:activity-compose:1.5.0'

but still I faced this same error.

The reason was that by viewModels() must be called inside the onCreate():

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val customViewModel: MyViewModel by viewModels()

        setContent {
            AppTheme {
                Surface() {
                    MyApp(customViewModel = customViewModel)
                }
            }
        }
    }
}

and not in any other composable function. But I was trying to calling it from MyApp() composable function. Hence the error.

Related