peresisUser
peresisUser

Reputation: 1686

Pass App context to Koin from Java Application class

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.

Upvotes: 3

Views: 3612

Answers (2)

Azamat Mahkamov
Azamat Mahkamov

Reputation: 1090

Create Kotlin klass (JavaKoinApplication.kt)

fun start(myApplication: Application) {
startKoin(listOf(module)) with (myApplication)}

then Call this class in your Java Application Class

JavaKoinApplication.start(this);

Upvotes: 0

Jin
Jin

Reputation: 31

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

Upvotes: 1

Related Questions