简体   繁体   English

我可以用 Hilt 注入变量的值吗?

[英]Can I inject a value of a variable with Hilt?

For instance...I have this:例如......我有这个:

@InstallIn(ApplicationComponent::class)
@Module

object AlarmInjection {

    @Provides
    @Singleton
    fun proverToday(): Calendar {
        return Calendar.getInstance()
    }

}

And in my class, I try to use the variable, which is injected by:在我的 class 中,我尝试使用由以下方式注入的变量:

    @AndroidEntryPoint
    class AlarmFragment : Fragment() {
    
        @Inject lateinit var today : Calendar

....


}

and I get a runtime error when I try to use the today variable.当我尝试使用 today 变量时出现运行时错误。 It says lateinit property is not instantiated.它说 lateinit 属性没有被实例化。

kotlin.UninitializedPropertyAccessException: lateinit property today has not been initialized

So, I have to use lateinit to inject anything with hilt, so theorecally is hasnt received value yet.所以,我必须使用 lateinit 来注入任何带有刀柄的东西,所以理论上还没有收到价值。 But, the injection itself provides an instance of the Calendar class.但是,注入本身提供了日历 class 的实例。

How can I solve this?我该如何解决这个问题?

Same code is working fine in my case.在我的情况下,相同的代码工作正常。

Have you annotated @AndroidEntryPoint on the activity also which uses this fragment?您是否在也使用此片段的活动上注释@AndroidEntryPoint

As per android documentation for hilt, activity must also be annotated with @AndroidEntryPoint which uses this fragment:根据android 文档的刀柄,活动还必须使用使用此片段的@AndroidEntryPoint进行注释:

If you annotate an Android class with @AndroidEntryPoint, then you also must annotate Android classes that depend on it.如果您使用 @AndroidEntryPoint 注释 Android class,那么您还必须注释依赖于它的 Android 类。 For example, if you annotate a fragment, then you must also annotate any activities where you use that fragment.例如,如果您注释一个片段,那么您还必须注释您使用该片段的任何活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM