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

标签 android android-viewmodel dagger-hilt

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/

相关文章:

android - 多次调用 livedata observe 的 onChanged 方法

android - Singleton 类应该使用什么?来自 Dagger 的真正的 Singleton 或 @Singleton 注释?

android - 注入(inject)到 Hilt 未实例化的任意 Logic 类中

android - 使 screenOrientation 可配置?

java.lang.UnsatisfiedLinkError : Couldn't load STLport_shared: findLibrary returned null (tess-two) 错误

java - ViewPager2/Tabs 问题与 ViewModel 状态

android - Dagger - 刀柄 : Do we need to mark all activities with @AndroidEntryPoint

java - 我可以将 "Ctrl"键添加到我的自定义 Android 键盘吗?

android - 通过 Android 设备读取 RFID

Android 获取ViewModelScope,用于接口(interface)委托(delegate)