Home > Blockchain >  Questions regarding sharedPreferences (Kotlin)
Questions regarding sharedPreferences (Kotlin)

Time:12-05

I am experimenting around with Kotlin's sharedPreferences, however I cannot seem to get the updated value to stick.

    val sharedPreferences = getSharedPreferences("Files", Context.MODE_PRIVATE)
    val editor = sharedPreferences.edit()
    editor.putInt("numbers",1).apply()
    val textview = findViewById<TextView>(R.id.textview)
    textview.text = sharedPreferences.getInt("numbers",0).toString()
    val button = findViewById<Button>(R.id.button)

    button.setOnClickListener {
        editor.putInt("numbers",2).apply()
        textview.text = sharedPreferences.getInt("numbers",0).toString()
    }

In the code above I set the initial value of the sharedPreference to 1, upon clicking the button the value will be updated to 2 and displayed.That works fine however when closing the app and reopening it, the value reverts to 1. Is there a way to permanatly keep the updated value?

CodePudding user response:

You are setting it to that value every time you open the activity, since onCreate() is called every time it opens. You should check if the value is already set, and if it is, skip that line of code.

if ("numbers" !in sharedPreferences) {
    val editor = sharedPreferences.edit()
    editor.putInt("numbers",1).apply()
}

By the way, there is an extension function for editing without having to call apply and editor. repeatedly:

if ("numbers" !in sharedPreferences) {
    sharedPreferences.edit {
        putInt("numbers",1)
    }
}
  • Related