Dagger Hilt — ViewModelClass has no zero argument constructor — causes

Daniel Zolnai
2 min readFeb 2, 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 {

val viewModel by viewModels<NameInputViewModel>()
...}

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"

Different dependency versions

As per the comments under this article, this seems to be a common issue as well. There are multiple places where the Dagger Hilt dependency is defined, and they all need to be on the same version:

  • The plugin classpath definition on the top-level build.gradle
  • The hilt-android dependency (implementation)
  • The hilt-compiler dependency (kapt)

I recommend using an ext.dagger_hilt_version variable, in the top-level build.gradle, which you then reference in all the other places.

Did you have the same exception, and something else was the cause? Feel free to add it as a comment!

--

--