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
You need to upgrade to Fragment 1.2.0 or higher.
As per the Lifecycle 2.2.0 release notes, the new ViewModelProvider
APIs that Hilt uses under the hood only apply when using Fragment 1.2.0 or higher. When using an older version of Fragments, those APIs are not connected to fragments and therefore your Hilt enabled ViewModel factory is not used when you use by viewModels()
.
You should upgrade to Fragment 1.2.5 (the last version of the Fragment 1.2.X set) or to Fragment 1.3.0, both of which contain the necessary API hooks to get Hilt working.