HiltViewModel:无法创建类的实例
我正在使用刀柄。更新后,1.0.0-alpha03我收到了@ViewModelInject已弃用的警告,我应该使用@HiltViewModel. 但是当我改变它时,我得到了一个错误:
java.lang.RuntimeException: Cannot create an instance of class com.example.LoginViewModel
...
Caused by: java.lang.NoSuchMethodException: com.example.LoginViewModel.<init> [class android.app.Application]
java.lang.RuntimeException: Cannot create an instance of class com.example.LoginViewModel
...
Caused by: java.lang.NoSuchMethodException: com.example.LoginViewModel.<init> [class android.app.Application]
以前我的 ViewModel 看起来像这样:
现在它看起来像这样:
class LoginViewModel @ViewModelInject constructor(
application: Application,
private val repository: RealtimeDatabaseRepository
) : AndroidViewModel(application)
注入 ViewModel 的片段:
@HiltViewModel
class LoginViewModel @Inject constructor(
application: Application,
private val repository: RealtimeDatabaseRepository
) : AndroidViewModel(application)
注入类:
@AndroidEntryPoint
class LoginFragment : Fragment(R.layout.fragment_login)
{
private val viewModel: LoginViewModel by activityViewModels()
}
当我private val repository: RealtimeDatabaseRepository从 ViewModel 构造函数中删除它时它正在工作
正如USMAN osman 所建议的那样,2.30.1-alpha当我更新到 时,我使用的是刀柄版本,错误消失了。2.31.2-alpha
回答
有了新的刀柄版本,很多东西都被改变了。
您还必须将您的 hilt android、hilt 编译器和 hilt gradle 插件升级为:2.31-alpha
我完全按照您所做的方式制作了模拟示例,我遇到了同样的问题,在浏览了 hilt 的文档后,我找到了将依赖项注入到 viewModels 的新方法,您必须制作将要注入到viewModel具有特殊组件的依赖项的单独模块,称为ViewModelComponent:
@Module
@InstallIn(ViewModelComponent::class) // this is new
object RepositoryModule{
@Provides
@ViewModelScoped // this is new
fun providesRepo(): ReposiotryIMPL { // this is just fake repository
return ReposiotryIMPL()
}
}
这是文档所说的ViewModelComponent和ViewModelScoped
All Hilt View Models are provided by the ViewModelComponent which follows the same lifecycle as a ViewModel, i.e. it survives configuration changes. To scope a dependency to a ViewModel use the @ViewModelScoped annotation.
A @ViewModelScoped type will make it so that a single instance of the scoped type is provided across all dependencies injected into the Hilt View Model.
链接:https : //dagger.dev/hilt/view-model.html
那么你的视图模型:
@HiltViewModel
class RepoViewModel @Inject constructor(
application: Application,
private val reposiotryIMPL: ReposiotryIMPL
) : AndroidViewModel(application) {}
更新
您应该使用ViewModelComponent或不是强制性的,ViewModelScoped就像我在上面的例子中所做的那样。您也可以使用其他scopes或components取决于您的用例。
此外阅读文档,我把匕首刀柄的链接放在上面。
- Omg, I forgot to update the kapt and I struggled like 5 hours finding the solution to why this is not working ... after reading the answer 5 times I figured it out, triple check the versions if your app crash