gpt4 book ai didi

android - 刀柄 : lateinit property repository has not been initialized in ViewModel

转载 作者:行者123 更新时间:2023-12-04 11:30:41 28 4
gpt4 key购买 nike

我在带有 HILT 的多模块 android 项目中面临这个问题。

 kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialized in MyViewModel
我的模块是
  • 应用模块
  • Viewmodel 模块
  • 用例模块
  • 数据源模块

  • '应用模块'
    @AndroidEntryPoint
    class MainFragment : Fragment() {
    private lateinit var viewModel: MainViewModel
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View {
    return inflater.inflate(R.layout.main_fragment, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    viewModel.test()
    }}
    'ViewModel 模块'
    class MainViewModel @ViewModelInject constructor(private val repository: MyUsecase): ViewModel() {
    fun test(){
    repository.test()
    }}
    '用例模块'
    class MyUsecase @Inject constructor() {

    @Inject
    lateinit var feature: Feature

    fun doThing() {
    feature.doThing()
    }

    @Module
    @InstallIn(ApplicationComponent::class)
    object FeatureModule {
    @Provides
    fun feature(realFeature: RealFeature): Feature = realFeature
    }
    }
    “数据源模块”
    interface Feature {
    fun doThing()
    }

    class RealFeature : Feature {
    override fun doThing() {
    Log.v("Feature", "Doing the thing!")
    }
    }
    依赖项是
    MyFragment ---> MyViewModel ---> MyUseCase ---> DataSource
    我对这段代码做错了什么,请纠正它。

    最佳答案

    在您的 Activity 类上方,您必须添加注释 @AndroidEntryPoint
    如下:
    @AndroidEntryPoint
    类 MainActivity : AppCompatActivity() {

    关于android - 刀柄 : lateinit property repository has not been initialized in ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62826677/

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