Hello, I'm trying to inject view model using Hilt, but I get the following error:

 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.wordssample, PID: 25250
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wordssample/com.example.wordssample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.wordssample.MainViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
  
 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.wordssample.MainViewModel
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
    at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
    at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
    at androidx.hilt.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:74)
    at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:69)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 

This is my MainActivity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
   
    private val viewModel  by viewModels<MainViewModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
      ....

And this is the ViewModel class I'm trying to inject

class MainViewModel @ViewModelInject constructor(
    @ApplicationContext application: Context,
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val repositorio = WordRepositorio(application)

    val allWords = repositorio.mAllWords
...

谢谢你的帮助!

推荐答案

Yes, there was nothing wrong with the code. The problem was in some libraries, apparently I was missing something.

I solved it by adding:

implementation 'com.google.dagger:hilt-android:2.28-alpha'

implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'

kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'

kapt 'com.google.dagger:hilt-android-compiler:2.28-alpha'

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'

Kotlin相关问答推荐

有什么原因,我得到一个空相关的错误在这个代码

Kotlin是否针对范围和进度优化sum()?

为什么";";.equals(1)在柯特林语中是有效的,但";";=1是无效的?

KTOR';S函数`staticResources`在Kotlin本机目标上不可用

如何修改muableStateMapOf的值?

generic 类实例列表 - 调用采用 T 的函数

Gradle:无法创建 ExtensiblePolymorphicDomainObjectContainer

在 kotlin 中使具体化字段可选

Kotlin 接口类型参数

如何将 `when` 与 2 个密封类一起使用并获取内部值?

为什么 Kotlin 的 null 安全性不能与局部变量初始化器一起正常工作?

如何在 Kotlin 中实现 Composition UML 关系?

如何通过 compose 处理剪切区域?

是什么让 Kotlin 中的 String 类能够使用方括号?

Kotlin 的 isNullOrBlank() 函数是否可以导入 xml 以用于数据绑定

Kotlin:sealed class cannot "contain" data classes?

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

如何在Kotlin中获得KType?

查找是否在列表中找到具有特定属性值的元素

从 Kotlin 访问 Integer.class