android – ViewModel in Kotlin: Unresolved Reference-ThrowExceptions

Exception or error:

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?

How to solve:

Include the following as a dependency:

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

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 addition to what Sup suggested, you’ll have to correct lifecycler:compiler to lifecycle:compiler – the Gradle sync shouldn’t even complete successfully with this typo.

Secondly, the standard android annotation processing (“annotationProcessor”) doesn’t really work with Kotlin. Instead, use Kotlin’s kapt.

At the top of your build.gradle file, add the following:

apply plugin: 'kotlin-kapt'.

And in your dependencies section, replace occurences of annotationProcessor (like the above one) with kapt, e.g.

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

###

If the above “adding/updating dependecies” did not resolve your issue then try to restart your android studio. It´s just to root, I do not see any major issue with it. Hope it helps.

###

I faced this kind of problem in AndroidStudio 3.0.1 and solved by adding
following dependencies in the proper build.gradle:

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

version code may be different as AndroidStudio tells you if it differs.

###

This can also be resolved by targeting minSdkVersion to 21.

If you have minSdkVersion 21 or higher, you won’t need implementation "android.arch.lifecycle:extensions:1.1.1".

Leave a Reply

Your email address will not be published. Required fields are marked *