Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android Kotlin – Saving Preferences (key value pair) – not working for me

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

Garrett

>Solution :

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()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading