Home:ALL Converter>Pass App context to Koin from Java Application class

Pass App context to Koin from Java Application class

Ask Time:2019-09-16T15:17:34         Author:peresisUser

Json Formatter

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.

Author:peresisUser,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57952030/pass-app-context-to-koin-from-java-application-class
Jin :

Based on the latest version 2.0.1 standard\n\nin AppModult.kt\n\nval appContext = module {\n single(named(\"appContext\")) { androidContext() }\n}\n\n\nin Application.kt\n\nstartKoin {\n androidContext(this@App)\n androidFileProperties()\n modules(listOf(appContext))\n }\n",
2019-09-16T07:45:44
yy