Home > Net >  Android Kotlin - Saving Preferences (key value pair) - not working for me
Android Kotlin - Saving Preferences (key value pair) - not working for me

Time:07-17

I am trying various simple Android Kotlin examples, to save some persistent data in my app. To start, I am using a straight forward example of writing one key-value pair, and reading it back. here's my code, in my activity's OnCreate()

val sharedPrefFile = "MyPrefFile"
val sharedPreferences: SharedPreferences = this.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE)
fun setPref()
{
    val editor = sharedPreferences.edit()
    val myName = "Elvis"
    editor.putString("nameFirst_key", myName)
}
fun getPref()
{
    val myName = sharedPreferences.getString("nameFirst_key", "no_name")
 }
getPref()
setPref()
getPref()

I would expect the first getPref() call to read "no_name", which it does. However, I was hoping the second getPref() call would read "Elvis", but it doesn't - it reads "no_name".

Can anyone tell me what I am doing wrong please?

Thanks

Garrett

CodePudding user response:

You are not calling commit() or apply() on editor, so the edits are not taking effect. This is covered in the documentation.

So, setPref() should be:

fun setPref()
{
    val editor = sharedPreferences.edit()
    val myName = "Elvis"
    editor.putString("nameFirst_key", myName).apply()
}
  • Related