Search code examples
androidkotlinsharedpreferences

getDefaultSharedPreferences(this) generates null error at runtime?


I am trying to setup a listener in my main activity for a change in the "force_dark" setting

val preferences = getDefaultSharedPreferences(this)

var listener: SharedPreferences.OnSharedPreferenceChangeListener =
    SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
        if (key == "force_dark") {
            Toast.makeText(this,"config changed",Toast.LENGTH_SHORT).show()
        }
    }


override fun onResume() {
    super.onResume()
    preferences.registerOnSharedPreferenceChangeListener(listener)
}

override fun onPause() {
    super.onPause()
    preferences.unregisterOnSharedPreferenceChangeListener(listener)
}

My test code is above but although it compiles, it crashes on "val preferences = getDefaultSharedPreferences(this)" with the error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference"

I dont understand why this is happening, it is the system shared preferences so how can it be null ? Can anybody clarify where I am going wrong ?


Thank you for your help, I managed to get it working but just want to check I got it working in the "correct" way, I added

lateinit var preferences : SharedPreferences
lateinit var listener : SharedPreferences.OnSharedPreferenceChangeListener

At the start, then

    preferences = getDefaultSharedPreferences(this)

    listener =
        SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
            if (key == "force_dark") {
                Toast.makeText(this,"config changed",Toast.LENGTH_SHORT).show()
            }
        }

In onCreate as suggested and then

override fun onResume() {
    super.onResume()
    preferences.registerOnSharedPreferenceChangeListener(listener)
}

override fun onPause() {
    super.onPause()
    preferences.unregisterOnSharedPreferenceChangeListener(listener)
}

By themselves, is there a more elegant solution or is this the best way ?


Solution

  • You're trying to use your activity as a Context too early. The activity is not yet set up as a context at instance init phase.

    Move the getDefaultSharedPreferences() call to onCreate() or later in the activity lifecycle.