Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hilt ViewModel has no zero argument constructor

Cannot create an instance of class com.comp.app.winners.WinnersViewModel
Caused by: java.lang.InstantiationException: java.lang.Class<com.comp.app.winners.WinnersViewModel> has no zero argument constructor

Getting an error when trying to resolve a viewmodel on a fragment using hilt

// Proj
ext.hilt_version = '2.32-alpha'
ext.lifecycle_version = "2.2.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"

// App
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
kapt "com.google.dagger:hilt-compiler:$hilt_version"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha03'
implementation "androidx.fragment:fragment-ktx:1.1.0"

@HiltAndroidApp
class MyApplication : Application()

@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule {
    @Provides
    fun provideService(): MyService = MyServiceImpl()
}

@AndroidEntryPoint
class HomeActivity : AppCompatActivity() {

    // Fragment is added here
    private fun openFragment(fragment: Fragment) =
        supportFragmentManager.beginTransaction().apply {
            replace(R.id.container, fragment)
            addToBackStack(null)
            commit()
        }
}

@AndroidEntryPoint
class WinnersFragment: Fragment() {
    private val viewModel: WinnersViewModel by viewModels()
}

@HiltViewModel
class WinnersViewModel @Inject constructor(
    private val service: MyService
) : ViewModel()

Is there something else to be done with the fragment? Do i need to provide the viewModel somehow?

NOTE: This is a crash/runtime-error, not a compile error

like image 466
aryaxt Avatar asked Feb 19 '26 20:02

aryaxt


1 Answers

My issue was nothing to do with my ViewModel, but to do with the fragment it was being applied to.

My ViewModel looks like

@HiltViewModel
class MyViewModel @Inject constructor(repository: MyRepository): ViewModel() {

This is correct, but I still got the exception Caused by: java.lang.InstantiationException: java.lang.Class<com.myapp.MyViewModel> has no zero argument constructor

However, I'd missed the AndroidEntryPoint annotation on the fragment. Adding this back in fixed the problem for me, i.e.

@AndroidEntryPoint
class MyFragment: Fragment() {

    private val viewModel: MyViewModel by viewModels()

    ...
}
like image 152
deanWombourne Avatar answered Feb 21 '26 09:02

deanWombourne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!