How to invoke getSharedPreferences outside the onCreate function in Kotlin?

Viewed 42

Context


I'm currently building an app that allow people to create a "What To Do" list and checked the completed item in the list by tapping on that item.

This is the function that will be called when the button is clicked:

fun onClickButton(button: Button) {
    var sharedPref = getSharedPreferences(packageName + "_preferences", Context.MODE_PRIVATE)
    sharedPref.getString("store_list", "NO_LIST")
    // ...
}

And this is a snippet of the full code (MainActivity.kt)

class MainActivity : AppCompatActivity() {
    fun onClickButton(button: Button) {
        var sharedPref = getSharedPreferences(packageName + "_preferences", Context.MODE_PRIVATE)
        val list sharedPref.getString("store_list", "NO_LIST")
        // ...
    }
    // ...
}

Problem


When I click one of the item, the app crashed and the log returned an error:

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

Solution I've tried


I've tried putting the sharedPref outside the function and in the MainActivity class as a null variable, then declaring the varible inside the onCreate function, like this:

class MainActivity : AppCompatActivity() {
    var sharedPref: SharedPreferences? = null
    fun onClickButton(button: Button) {
        var sharedPref = getSharedPreferences(packageName + "_preferences", Context.MODE_PRIVATE)
        val list = sharedPref?.getString("store_lock_app", "NO_CONFIG")
        if (list != null) {
            Log.d("list", list)
        }
        // ...
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        sharedPref = getSharedPreferences(packageName + "_preferences", Context.MODE_PRIVATE)
        // ...
    }
    // ...
}

And when I click the item, the list output return null:

D/list: null

Conclusion


So, is there any way to invoke getSharedPreferences outside the onCreate function? (Also, all of this is inside the same Activity)

0 Answers
Related