Hilt Dagger 错误 java.lang.RuntimeException:无法创建 class HomeFragmentViewModel 的实例
Hilt Dagger Error java.lang.RuntimeException: Cannot create an instance of class HomeFragmentViewModel
我试图将我的 viewModel 注入到片段中,但我遇到了这个错误:
java.lang.RuntimeException: 无法创建 class com.mas.cryptomasters.ui.fragment.home.HomeFragmentViewModel
的实例
我的代码:
class HomeFragment : BaseFragment<FragmentHomeBinding>() {
private val viewModel: HomeFragmentViewModel by viewModels()
override fun init() {
viewModel.homeMutable.observe(this) {
when {
it.reLogin -> requireActivity().reLogin()
it.error.isNotEmpty() -> requireContext().crToast()
it.data != null -> Log.e("TAG", "data != null")
}
}
}
}
这是我的 ViewModel class
@HiltViewModel
class HomeFragmentViewModel @Inject constructor(apiRepository: ApiRepository) :
ViewModel() {
val homeMutable: MutableLiveData<Response> = MutableLiveData()
init {
viewModelScope.launch {
apiRepository.getHome()
.let {
when (it.isRequestSuccess(it.body()!!.code)) {
RESPONSE.SUCCESS -> homeMutable.postValue(Response(it.body()!!))
RESPONSE.ERROR -> homeMutable.postValue(Response(error = "${it.errorBody()}"))
RESPONSE.AUT -> homeMutable.postValue(Response(reLogin = true))
}
}
}
}
}
- 确保您的 activity 和片段有
@AndroidEntryPoint
注释。
- 将
implementation "androidx.fragment:fragment-ktx:1.4.1"
添加到 build.gradle(:app)
我试图将我的 viewModel 注入到片段中,但我遇到了这个错误:
java.lang.RuntimeException: 无法创建 class com.mas.cryptomasters.ui.fragment.home.HomeFragmentViewModel
的实例我的代码:
class HomeFragment : BaseFragment<FragmentHomeBinding>() {
private val viewModel: HomeFragmentViewModel by viewModels()
override fun init() {
viewModel.homeMutable.observe(this) {
when {
it.reLogin -> requireActivity().reLogin()
it.error.isNotEmpty() -> requireContext().crToast()
it.data != null -> Log.e("TAG", "data != null")
}
}
}
}
这是我的 ViewModel class
@HiltViewModel
class HomeFragmentViewModel @Inject constructor(apiRepository: ApiRepository) :
ViewModel() {
val homeMutable: MutableLiveData<Response> = MutableLiveData()
init {
viewModelScope.launch {
apiRepository.getHome()
.let {
when (it.isRequestSuccess(it.body()!!.code)) {
RESPONSE.SUCCESS -> homeMutable.postValue(Response(it.body()!!))
RESPONSE.ERROR -> homeMutable.postValue(Response(error = "${it.errorBody()}"))
RESPONSE.AUT -> homeMutable.postValue(Response(reLogin = true))
}
}
}
}
}
- 确保您的 activity 和片段有
@AndroidEntryPoint
注释。 - 将
implementation "androidx.fragment:fragment-ktx:1.4.1"
添加到build.gradle(:app)