Home > Software design >  Android shared preference, Kotlin
Android shared preference, Kotlin

Time:12-30

I have the following simple code. It takes the value of a textbox, saves it and retrieve. The retrieved value is not the same as the saved one.

The printout: value: qwert asdf

What the problem could be?

val sharedPref = getSharedPreferences("Data", Context.MODE_PRIVATE)
sharedPref.edit().putString("Str",binding.text.editText?.text.toString())
print("Value: ")
println(binding.text.editText?.text.toString())
sharedPref.edit().commit()
println(sharedPref.getString("Str","asdf"))

Thank you for any hints in advance

CodePudding user response:

SharedPreferences#edit hands you an instance of a SharedPreferences.Editor class on which you're calling the putString method but you're not committing any changes there.

Your second sharedPref.edit().commit() just gets a new instance of SharedPreferences.Editor without any editions and calls commit with no changes.

Try the following

val editor = sharedPrefs.editor()

editor.putString("key", "value")
editor.commit()

return sharedPrefs.getString("key", "defaultValue")

A more idiomatic approach would be to use the apply function from the kotlin stdlib:

sharedPrefs.edit().apply {
  putString("key", "value")
  commit()
}

CodePudding user response:

You can also try like this

//For Add String Value in sharedPreferences
    val sharedPreferences = getSharedPreferences("key", MODE_PRIVATE) ?: return
    with(sharedPreferences.edit()) {
        putString("yourStringKey", "Hello World")
        apply()
    }
    
//Here get enter string value from sharedPreferences other activity 
    val sharedPreferences1 = getSharedPreferences("key", MODE_PRIVATE) ?: return
    val string = sharedPreferences1.getString("yourStringKey", "hi") //"hi" is default value
    Log.e("sharedPreferences1", "sharedPreferences1 Val is -->> $string")

For More Information, you can refer to official android documentation here

  • Related