简体   繁体   中英

Kotlin dagger hilt injection is not initialized

i am trying to use dagger hilt, i set up everything, but i am getting and error when i try to use the object for witch i am created a dependency injection: kotlin.UninitializedPropertyAccessException: lateinit property exoPlayer has not been initialized

Here is my module provider:

@Module
@InstallIn(ServiceComponent::class)
object ServiceModule {
    @ServiceScoped
    @Provides
    fun provideExoPlayer(
        @ApplicationContext context: Context,
        audioAttributes: AudioAttributes
    ) = SimpleExoPlayer.Builder(context).build().apply {
        setAudioAttributes(audioAttributes, true)
        setHandleAudioBecomingNoisy(true)
    }
}

In my activity i got:

@AndroidEntryPoint
class AudioActivity : AppCompatActivity(), Player.EventListener { {

    @Inject
    lateinit var exoPlayer: SimpleExoPlayer

then i try to add a listener in the onCreate

exoPlayer.addListener(this)

But here i got the error that it's not initialized, i don't realy understand because i though that the all point of dependency injection was to provide an construct that can be injected everywhere. So why it has not been initialized?

You're actually providing your SimpleExoPlayer object in ServiceComponent . As you're expecting to inject the SimpleExoPlayer in Activity, you should provide it in ActivityComponent instead. I think you may need a module or reuse existing one

@Module
@InstallIn(ActivityComponent::class)
object ActivityModule {
    
    @ActivityScoped
    @Provides
    fun provideExoPlayer(
        @ApplicationContext context: Context,
        audioAttributes: AudioAttributes
    ) = SimpleExoPlayer.Builder(context).build().apply {
        setAudioAttributes(audioAttributes, true)
        setHandleAudioBecomingNoisy(true)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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