Search code examples
javaandroidkotlinsharedpreferences

MainApplication class used as a global context crashes if declared in Kotlin vs Java


I have a MainApplication class declared in the AndroidManifest.xml

    <application
    android:name=".MainApplication" ...other stuffs >

that I used as a global context for my app accessible outside of any Activity or Fragment.

if I declare my MainApplication class as:

public class MainApplication extends Application {

private static MainApplication instance;

public MainApplication() {
    instance = this;
}

public static MainApplication shared() {
    return instance;
}

}

Everything is fine, and I can then use it then like this:

val c = MainApplication.shared()
return c.getSharedPreferences(prefsKey, Context.MODE_PRIVATE)

However if I declare the same class as a Kotlin class and call MainApplication.shared I get an error saying I'm calling sharedPreferences on null object

class MainApplication: Application() {
companion object {
    @JvmStatic
    val shared: MainApplication = MainApplication()
}

Is there an issue with Kotlin class declaration and singleton (SharedInstances) or Am I making an error trying to declare this class like this?


Solution

  • The problem is that you are creating an instance of the Application class. It should be something like this:

    class MainApplication : Application() {
    
        override fun onCreate() {
            super.onCreate()
    
            appContext = applicationContext
        }
    
        companion object {
            lateinit var appContext: Context
        }
    }