Skip to content or footer

Dagger Hilt — ViewModelClass has no zero argument constructor — causes

If you are using Dagger Hilt on your Android project, you’ve probably seen this exception when opening a screen. It is not really helpful, and you can lose quite some time finding the culprit, so here I list the most common causes I had when I got this exception.

Dagger Hilt — ViewModelClass has no zero argument constructor — causes Dawn Technology
Author

Dániel Zolnai

Date

25 January 2021


If you are using Dagger Hilt on your Android project, you’ve probably seen this exception when opening a screen. It is not really helpful, and you can lose quite some time finding the culprit, so here I list the most common causes I had when I got this exception.

Missing @AndroidEntryPoint on your Fragment / Activity

In each activity and fragment where you inject your ViewModel, you need to annotate the class with this annotation:

@AndroidEntryPoint class NameInputDialogFragment : Fragment

This is quite easy to forget, and happens with even the best of us

Missing @ViewModelInject on ViewModel constructor (now deprecated)

Another frequent thing we forget. Instead of just a regular constructor with parameters, we need to add an annotation now:

class HomeViewModel @ViewModelInject constructor( private val databaseRepository: DatabaseRepository, … ) : ViewModel()

Missing @HiltViewModel on ViewModel (from 2.31+)

If you are on Dagger 2.31 or higher, the new way to inject into ViewModels instead of the @ViewModelInject approach is to annotate the class with @HiltViewModel and add an @Inject constructor:

@HiltViewModel
class HomeViewModel @Inject constructor(     private val databaseRepository: DatabaseRepository,     … ) : ViewModel()

Missing compiler dependency

This can happen if you just started a new project, and forgot to include the kapt compiler which generates all the code for injecting the ViewModels.

You probably added the Dagger Hilt compiler, but forgot about the androidx-hilt one:

implementation “com.google.dagger:hilt-android:$dagger_hilt_version” kapt “com.google.dagger:hilt-compiler:$dagger_hilt_version” kapt “androidx.hilt:hilt-compiler:$androidx_hilt_version” implementation “androidx.hilt:hilt-lifecycle-viewmodel:$androidx_hilt_version”

 

Stuck on a Technical Issue?

Tell us where you’re blocked. Dawn Technology helps you solve complex Android challenges fast.