Cannot create instance of viewmodel after using Hilt in Android

This is caused by a version mismatch between AndroidX Lifecycle, AndroidX Core, AndroidX Activity and AndroidX Fragment.

Hilt only works if getDefaultViewModelProviderFactory can be overridden.

This is only true if that method actually exists, which it doesn't if your dependencies are out of date. Namely, your androidx.fragment is lower than 1.2.0, and your androidx.activity is lower than 1.1.0.

Use this and it'll work:

implementation "androidx.appcompat:appcompat:1.4.1"
implementation "androidx.core:core-ktx:1.7.0"
implementation "androidx.activity:activity-ktx:1.4.0"
implementation "androidx.fragment:fragment-ktx:1.4.1"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'

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

But currently, this is what makes it work for me:

buildscript {
    ext {
        dagger_version = '2.41'
    }

dependencies {
    classpath "com.google.dagger:hilt-android-gradle-plugin:$dagger_version"
}

and

apply plugin: 'dagger.hilt.android.plugin'
apply plugin: 'kotlin-kapt'

implementation "com.google.dagger:dagger:$dagger_version"
kapt "com.google.dagger:dagger-compiler:$dagger_version"
implementation "com.google.dagger:hilt-android:$dagger_version"
kapt "com.google.dagger:hilt-android-compiler:$dagger_version"
kaptTest "com.google.dagger:hilt-android-compiler:$dagger_version"
kaptAndroidTest "com.google.dagger:hilt-android-compiler:$dagger_version"
kapt 'androidx.hilt:hilt-compiler:1.0.0'

@ViewModelInject is deprecated in the newer hilt version

Reference

Use HiltViewModel

@HiltViewModel
class AllFilesListViewModel @Inject constructor(
    val pdfItemRepository: PdfItemRepository)
) : ViewModel() {

}

This got solved after I used kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01' in app's build.gradle. I had already added kapt "com.google.dagger:hilt-android-compiler:2.28-alpha". I still didn't understand the difference between two BTW. If anyone knows. Please explain it to me.


This happens to me when using Hilt , and that was because I forgot to add the @AndroidEntryPoint annotation on top of the fragment class. Both the fragment and the host activity should be annotated with this annotation.