Hilt 踩坑

35 阅读1分钟

无法创建ViewModel实例 Cannot create an instance of class ViewModel

编译正常,一运行就报如下异常。
java.lang.RuntimeException: Unable to start activity ComponentInfo{}: 
java.lang.RuntimeException: Cannot create an instance of class TestViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
Caused by: java.lang.NoSuchMethodException: com.example.viewui.TestViewModel.<init> []
	at java.lang.Class.getConstructor0(Class.java:3325)
	at java.lang.Class.getDeclaredConstructor(Class.java:3063)
	at androidx.lifecycle.viewmodel.internal.JvmViewModelProviders.createViewModel(JvmViewModelProviders.kt:38)

原因:

hilt放在了comon模块,通过api来传递的依赖,可能导致编译的时候hilt漏了一些东西。

我的项目结构如下:


解决方法:

使用hilt的模块直接用implementation依赖hilt库,不要使用api传递。