I am trying to implement ViewModel in a 100% Kotlin app. Every piece of documentation I can find says I want to use this to get the ViewModel instance:
ViewModelProviders.of(this).get(CustomViewModel::class.java)
According to the docs, I should be able to import this with:
import android.arch.lifecycle.ViewModelProviders
This import is unresolved though. I am using the following in my build file:
def androidArchVersion = '1.1.1' implementation "android.arch.lifecycle:viewmodel:$androidArchVersion" implementation "android.arch.lifecycle:livedata:$androidArchVersion" annotationProcessor "android.arch.lifecycler:compiler:$androidArchVersion" testImplementation "android.arch.core:core-testing:$androidArchVersion"
Why can't I access ViewModelProviders
?
To conclude, the unresolved reference error happens when Kotlin has no idea what the keyword you’re typing in the file points to. It may be a function, a variable, or another construct of the language that you’ve yet to declare in the code.
When you’re writing code for Android application and Kotlin, you may frequently encounter a static error from your IDE saying unresolved reference for a specific keyword or variable. For example, you can produce the error by calling a custom function that you haven’t defined in your code yet: Or when you assign a variable without declaring them:
Secondly, the standard android annotation processing ("annotationProcessor") doesn't really work with Kotlin. Instead, use Kotlin's kapt. apply plugin: 'kotlin-kapt'. And in your dependencies section, replace occurences of annotationProcessor (like the above one) with kapt, e.g.
The compiler does not resolve viewModels. I don't know what the problem is. Did I miss something? implementation "androidx.activity:activity-ktx:$activity_version" implementation "androidx.fragment:fragment-ktx:$fragment_version"
Include the following as a dependency:
implementation "android.arch.lifecycle:extensions:1.1.1"
The equivalent AndroidX dependency is:
"androidx.lifecycle:lifecycle-extensions:VERSION"
in where VERSION can be replaced for Current Stable, Beta or Alpha values given in this official link
This dependency is for both ViewModel and LiveData and thus would not require you to give separate dependencies for the same either; i.e. the first two dependencies indicated by you can be replaced by the aforementioned lifecycle extensions dependency.
In my case I was missing :
implementation "androidx.fragment:fragment-ktx:1.1.0"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With