26

I am learning kotlin using koin. While running the application in catlog I see the following message.

java.lang.IllegalStateException: KoinApplication has not been started

though I have used startKoin in MyApplication

class MyApplication : Application() {

    var listOfModules = module {
        single { GitHubServiceApi() }
    }

    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidLogger()
            androidContext(this@MyApplication)
            modules(listOfModules)
        }

    }

} 

enter image description here

Zoe
  • 27,060
  • 21
  • 118
  • 148
anandyn02
  • 259
  • 1
  • 3
  • 6

5 Answers5

14

Adding "android:name=".TheApplication" in the Manifest file solved the issue.

    android:name=".TheApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_app_icon_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.Shrine">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

"android:name=".TheApplication" is the Class Name from Koin

class TheApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        }

        startKoin {
            androidLogger()
            androidContext(androidContext = this@TheApplication)

            modules(
                listOfModules
            )
        }
    }
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Leonard
  • 147
  • 1
  • 6
6

In you manifest.xml,

<application>
    android:name=".MyApplication"
    ...
</application

Add this line in application tag.

Sohaib Ahmed
  • 1,990
  • 1
  • 5
  • 23
1

If you write unit test, you also should add startKoin and inject dependencies:

@Before
fun startKoinForTest() {
    startKoin {
        modules(DI.modules(...))
    }
}

@After
fun stopKoinAfterTest() = stopKoin()

See also Koin Android Test.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
0

Basically, you need to give the name of the class where you called startKoin() method, in the Manifest as an application name. And this will let your configure logging, properties loading and modules. Check this out: https://doc.insert-koin.io/#/koin-core/dsl

Xarybdis
  • 157
  • 6
0
private fun getKoin(activity: ComponentActivity): Koin {
return if (activity is KoinComponent) {
    activity.getKoin()
} else {
    GlobalContext.getOrNull() ?: startKoin {
        androidContext(activity)
        modules(listModule)
    }.koin
}

}

 fun ComponentActivity.contextAwareActivityScope() = runCatching {
LifecycleScopeDelegate<Activity>(
    lifecycleOwner = this,
    koin = getKoin(this)
)}.getOrElse { activityScope() 
}