I am trying to use SharedPreferences
as a storage for my 'favorite item ids'. I am using this in my Kotlin Android app.
When I call method for storing values into SharedPreferences
, I'd like to save Set
of Strings
. Values are present in the SharedPreferences
object anytime I check them in my application. But when I close the app (close the app on background or when app crashes) and then open the app again the content of SharedPreferences
is []
if I don't save anything in the SharedPreferences
during the app run. If I save something into SharedPreferences
close the app and open it once again it loads Set
with exactly one element [1]
.
It seems that anytime I store something in the SharedPreferences
using putStringSet()
a Set
with only one element [1]
is written int SharedPreferences
after the application crashes or is closed.
I've debugged the app many times, put the debug logs everywhere, but cannot find the reason.
Could anyone help?
I am not sure whether I need some permissions in AndroidManifest
or somewhere else?
To make a better picture of the app:
Iam using android Emulator (perhaps it requires some special settings?)
More activities are accessing the same SharedPreferences
, basically in one activity I write into it and in the other I read from it.
This method I am using for storing values into SharedPreferences:
fun saveFavorite(id: Long){
val favorites = sharedPreferences.getStringSet(preferencesKey, setOf<String>())
favorites.add(id.toString())
with (sharedPreferences.edit()) {
putStringSet(preferencesKey, favorites)
commit()
}
}
And this method I am using for getting values from SharedPreferences:
fun getFavorites(): Set<String>{
val favorites = sharedPreferences.getStringSet(preferencesKey, setOf<String>())
return favorites
}