gpt4 book ai didi

android - NoSuchMethodException 试图实例化 ViewModel

转载 作者:行者123 更新时间:2023-12-03 10:41:53 26 4
gpt4 key购买 nike

我正在尝试实例化我的 View 模型,但出现此错误

Caused by: java.lang.NoSuchMethodException: [class com.test.domain.PostUserTokenImpl] at java.lang.Class.getConstructor0(Class.java:2327) at java.lang.Class.getConstructor(Class.java:1725) at com.test.presentation.viewmodel.LoginVMFactory.create(LoginVMFactory.kt:13)



我尝试做一个持有和接口(interface)的 ViewModel 实例

看法
private val viewModel by lazy { ViewModelProviders.of(this, LoginVMFactory(PostUserTokenImpl(UserRepoImpl()))).get(LoginViewModel::class.java) }

登录VMFactory
class LoginVMFactory(private val useCase: PostUserTokenImpl):ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(PostUserTokenImpl::class.java).newInstance(useCase)
}
}

登录 View 模型
class LoginViewModel(private val useCase: PostUserToken): ViewModel() {
...
}

PostUserToken
interface PostUserToken {

suspend fun postUserToken(user: User): Resource<Boolean>
}

PostUserTokenImpl
class PostUserTokenImpl(private val repo: UserRepo): PostUserToken {

override suspend fun postUserToken(user:User):Resource<Boolean> = repo.saveUserToken(user)

}

知道为什么会这样吗?我怀疑这可能是因为我们不能用我们的 View 模型的接口(interface)实例化?

最佳答案

将我的实现更改为

class LoginVMFactory(private val useCase: PostUserToken):ViewModelProvider.Factory {

override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(PostUserToken::class.java).newInstance(useCase)
}
}

然后在我看来
private val viewModel by lazy { ViewModelProviders.of(this, LoginVMFactory(PostUserTokenImpl(UserRepoImpl()))).get(LoginViewModel::class.java) }

关于android - NoSuchMethodException 试图实例化 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59379305/

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