gpt4 book ai didi

android - Hilt ViewModel 没有零参数构造函数

转载 作者:行者123 更新时间:2023-12-04 23:41:24 55 4
gpt4 key购买 nike

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
尝试使用刀柄解析 fragment 上的 View 模型时出错
// 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()
fragment 还有其他事情要做吗?
我需要以某种方式提供 viewModel 吗?
注意:这是崩溃/运行时错误,而不是编译错误

最佳答案

我的问题与我的 ViewModel 无关,而是与它被应用到的 fragment 有关。
我的 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 fragment 上的注释。重新添加它为我解决了这个问题,即
@AndroidEntryPoint
class MyFragment: Fragment() {

private val viewModel: MyViewModel by viewModels()

...
}

关于android - Hilt ViewModel 没有零参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66197020/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com