Kotlin 匕首刀柄注入未初始化

问题描述 投票:0回答:2

我正在尝试使用匕首柄,我设置了所有内容,但是当我尝试使用该对象为女巫创建依赖项注入时出现错误:

kotlin.UninitializedPropertyAccessException: lateinit property exoPlayer has not been initialized

这是我的模块提供商:

@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)
    }
}

在我的活动中我得到:

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

    @Inject
    lateinit var exoPlayer: SimpleExoPlayer

然后我尝试在 onCreate 中添加一个监听器

exoPlayer.addListener(this)

但是在这里我得到了它没有初始化的错误,我不太明白,因为我认为依赖注入的全部目的是提供一个可以在任何地方注入的构造。那为什么还没有初始化呢?

android kotlin dependency-injection dagger dagger-hilt
2个回答
0
投票

您实际上是在

SimpleExoPlayer
中提供您的
ServiceComponent
对象。由于您希望在 Activity 中注入
SimpleExoPlayer
,因此您应该在
ActivityComponent
中提供它。我认为您可能需要一个模块或重用现有的模块

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

0
投票

您提到在

AudioActivity
中的
onCreate()
中您只是添加了一个侦听器。因此,鉴于您在应用程序/模块中正确设置了所有插件和依赖项,您可能忘记在活动中调用
super.onCreate()
(注入魔法发生的地方),这是在开始触摸任何注入字段之前需要的.

© www.soinside.com 2019 - 2024. All rights reserved.