Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass App context to Koin from Java Application class

Tags:

android

koin

I have a Java application class, I cannot change it to Kotlin. I init Koin like this:

   KoinApplication koinApp = KoinApplication.create()
            .printLogger()
            .modules(
                    myModule
            );
    start(koinApp);

My module is created in another file:

@JvmField
val myModule = module {
    single { DateUtil(androidContext()) }
    factory<ListPresenterContract> { MyListPresenter() }
}

But then when I access this file DateUtil I'm getting this error regarding androidContext():

Caused by: org.koin.android.error.MissingAndroidContextException: Can't resolve Context instance. Please use androidContext() function in your KoinApplication configuration.
at org.koin.android.ext.koin.ModuleExtKt.androidContext(ModuleExt.kt:33)
at koin.MyKoinModulesKt$MyModule$1$1.invoke(MyKoinModules.kt:16)
at koin.MyKoinModulesKt$MyModule$1$1.invoke(Unknown Source:4)
at org.koin.core.instance.DefinitionInstance.create(DefinitionInstance.kt:54)
at org.koin.core.instance.SingleDefinitionInstance.get(SingleDefinitionInstance.kt:40)
at org.koin.core.definition.BeanDefinition.resolveInstance(BeanDefinition.kt:70)
at org.koin.core.scope.Scope.resolveInstance(Scope.kt:165)
at org.koin.core.scope.Scope.get(Scope.kt:128)
at view.MyViewerListAdapter$$special$$inlined$inject$1.invoke(Scope.kt:327)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at view.MyViewerListAdapter.getDateUtil(Unknown Source:7)
at view.MyViewerListAdapter.setModelView(MyListAdapter.kt:77)
at view.MyViewerListAdapter.onBindViewHolder(MyViewerListAdapter.kt:45)
at view.MyViewerListAdapter.onBindViewHolder(MyListAdapter.kt:27)

I suspect that it just so happens that my module is initialised before the application class, and gets null for the androidContext. And only when I actually access the file that supposed to have context, it doesn't lazily initialise and I still have the null context. I don't know how to get around that in a Java app class so I removed the context from the module in the meantime.

like image 591
peresisUser Avatar asked Dec 07 '25 06:12

peresisUser


1 Answers

Based on the latest version 2.0.1 standard

in AppModult.kt

val appContext = module {
    single(named("appContext")) { androidContext() }
}

in Application.kt

startKoin {
            androidContext(this@App)
            androidFileProperties()
            modules(listOf(appContext))
        }
like image 112
Jin Avatar answered Dec 09 '25 19:12

Jin