Tarsila Costalonga
Tarsila Costalonga

Reputation: 1104

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:

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

....


}

and I get a runtime error when I try to use the today variable. It says lateinit property is not instantiated.

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. But, the injection itself provides an instance of the Calendar class.

How can I solve this?

Upvotes: 1

Views: 5082

Answers (1)

Manishoaham
Manishoaham

Reputation: 802

Same code is working fine in my case.

Have you annotated @AndroidEntryPoint on the activity also which uses this fragment?

As per android documentation for hilt, activity must also be annotated with @AndroidEntryPoint which uses this fragment:

If you annotate an Android class with @AndroidEntryPoint, then you also must annotate Android classes that depend on it. For example, if you annotate a fragment, then you must also annotate any activities where you use that fragment.

Upvotes: 1

Related Questions