Search code examples
androidkotlinsharedpreferences

getSharedPreferences is returning null on app startup with custom application


Currently, I have my own custom Application class that I have extended.

class CustomApplication : Application() {
    init {
        val x = getSharedPreferences("main", Context.MODE_PRIVATE)
    }
}

However, when I run the application, I get the following null pointer error.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

How is this possible? I am confused because when I consulted the documentation I see this:

public SharedPreferences getSharedPreferences(String name, int mode) {
    throw new RuntimeException("Stub!");
}

A method that should never return a null value! Anyone willing to help me out with this? 🤔


Solution

  • I got the Kotlin lifecycle init {...} mixed up with the Android lifecycle onCreate {...}.

    Posting this trivial solution in case anyone else also stumbles on this in the future.

    class CustomApplication : Application() {
        override fun onCreate() {
            super.onCreate()
    
            val x = getSharedPreferences("main", Context.MODE_PRIVATE)
        }
    }