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
尝试使用刀柄解析片段上的视图模型时出错
// 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()
这个片段还有什么要处理的吗? 我需要以某种方式提供 viewModel 吗?
注意:这是崩溃/运行时错误,而不是编译错误
答案 0 :(得分:2)
您需要升级到 Fragment 1.2.0 或更高版本。
根据 Lifecycle 2.2.0 release notes,Hilt 在幕后使用的新 ViewModelProvider
API 仅在使用 Fragment 1.2.0 或更高版本时适用。使用旧版本的 Fragment 时,这些 API 不会连接到 Fragments,因此在您使用 by viewModels()
时不会使用启用 Hilt 的 ViewModel 工厂。
您应该升级到 Fragment 1.2.5(Fragment 1.2.X 集的最后一个版本)或 Fragment 1.3.0,两者都包含使 Hilt 工作所需的 API 钩子。
答案 1 :(得分:1)
我的问题与我的 ViewModel 无关,而是与它应用到的片段有关。
我的 ViewModel 看起来像
@HiltViewModel
class MyViewModel @Inject constructor(repository: MyRepository): ViewModel() {
这是正确的,但我仍然收到异常 Caused by: java.lang.InstantiationException: java.lang.Class<com.myapp.MyViewModel> has no zero argument constructor
但是,我错过了片段上的 AndroidEntryPoint
注释。将其添加回来为我解决了问题,即
@AndroidEntryPoint
class MyFragment: Fragment() {
private val viewModel: MyViewModel by viewModels()
...
}