【问题标题】:Kotlin dagger hilt injection is not initializedKotlin 匕首刀柄注入未初始化
【发布时间】:2022-01-08 06:36:39
【问题描述】:

我正在尝试使用匕首柄,我设置了所有内容,但是当我尝试将对象用于女巫时出现错误,我创建了一个依赖注入: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)

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

【问题讨论】:

  • 您的应用程序类是否使用@HiltAndroidApp注解?
  • 你能在问题中添加你的onCreate函数吗?
  • 我的应用是hiltandroidapp,我在创建时只添加了now的监听器
  • 但我尝试过我的活动是我的 Exoplay 的事件监听器,所以它可能是为了那个?

标签: android kotlin dependency-injection dagger dagger-hilt


【解决方案1】:

您实际上是在ServiceComponent 中提供您的SimpleExoPlayer 对象。正如您期望在 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)
    }
}

【讨论】:

  • 我尝试将ServiceComponent更改为ApplicationComponent,但它不起作用我仍然收到错误:lateinit属性exoPlayer尚未初始化
  • 刚刚注意到您使用的是对象,如何使用类代替模块
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多