Step #2: Creating a Custom Application

We need to configure Koin and teach it what objects we want it to make available to the rest of our app.

In Android, the typical place to configure something like Koin is in a custom Application subclass. The Android framework creates a singleton instance of Application — or of a custom subclass — when your process starts. That Application object will be around for the life of the process. And, it has an onCreate() method where we can initialize libraries like Koin.

So, we need another Kotlin class.

Right-click over the com.commonsware.todo class where (presently) all of our Kotlin classes reside, and choose “New” > “Kotlin File/Class” from the context menu. Fill in ToDoApp for the “Name” and choose “Class” as the kind. Press Enter or Return, and you will get an empty ToDoApp class.

Then, modify it to have it extend from android.app.Application:

package com.commonsware.todo

import android.app.Application

class ToDoApp : Application() {
}

Next, open up the AndroidManifest.xml file. On the <application> element, add in an android:name attribute:

  <application
    android:name=".ToDoApp"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.ToDo">
    <activity
      android:name=".AboutActivity"
      android:exported="true" />
    <activity
      android:name=".MainActivity"
      android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

This tells the Android framework to use our subclass of Application, rather than Application itself, when it comes time to create this singleton.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.