gpt4 book ai didi

android - Dagger -2 "lateinit property application has not been initialized"

转载 作者:行者123 更新时间:2023-11-29 23:25:26 25 4
gpt4 key购买 nike

我试图在一个类中注入(inject)应用程序上下文

”lateinit property application has not been initialized"

异常。

核心模块.kt

@Module
open class CoreModule {
@Singleton
@Provides
fun provideRealmHelper(): RealmHelper {
return RealmHelper()
}
}

MyApplication.kt

open class MyApplication : MultiDexApplication(), HasActivityInjector {

@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

val log = LoggerFactory.getLogger(this.javaClass)!!

companion object {
var application: MyApplication? = null

fun getInstance(): MyApplication {
return application!!
}
}

override fun onCreate() {
try {
super.onCreate()
application = this
DaggerAppComponent.builder().application(this).build().inject(this)
} catch (e: Exception) {
log.error("Exception in Application", e)
Thread.setDefaultUncaughtExceptionHandler(GlobalExceptionHandler())
}

}

override fun activityInjector() = dispatchingAndroidInjector
}

AppComponent.kt

@Singleton
@Component(modules = [AndroidSupportInjectionModule::class,CoreModule::class])
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: MyApplication): Builder

fun build(): AppComponent
}

fun inject(myApplication: MyApplication)

fun inject(realmHelper: RealmHelper)
}

//我需要这个类中的应用上下文。我在这里注入(inject)applicationContext。注入(inject)是正确的方法还是我应该使用构造函数注入(inject)?

RealmHelper.kt

class RealmHelper @Inject constructor() {
//need application context here but getting "lateinit property application has not been initialized
@Inject
lateinit var application: MyApplication

init {
Realm.init(application) // null application
}
}

注意:MyApplication被添加到AndoridManifest.xml

最佳答案

问题是你注释了你的字段但没有注入(inject)。您可以像在应用程序类中那样注入(inject)字段:DaggerAppComponent.builder().application(this).build().inject(this)

或者您可以将您的应用程序字段移动到 RealmHelper 构造函数,并且在核心模块中您需要编写一个提供函数来返回应用程序。如果你想看一个例子,我有一个应用程序。 https://github.com/volkansahin45/Moneycim

关于android - Dagger -2 "lateinit property application has not been initialized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53664063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com