I am writing an Android app and have to save a StringSet as a SharedPreference. The relevant code looks like this:
dialog.setButton(DialogInterface.BUTTON_POSITIVE, if (remove) "Entfernen" else "Hinzufügen") { _, _ ->
val courses = prefs.getStringSet("filters", mutableSetOf())!!
if (remove) {
if (!courses.remove(course)) {
Toast.makeText(activity, "Konnte \"$course\" nicht entfernen", Toast.LENGTH_LONG).show()
return@setButton
}
} else if (!courses.add(course)) {
Toast.makeText(activity, "Konnte \"$course\" nicht hinzufügen", Toast.LENGTH_LONG).show()
return@setButton
}
dialog.dismiss()
val editor = prefs.edit()
editor.putStringSet("filters", courses)
Log.d("RecyclerViewAdapter", "Committed changed prefs: ${editor.commit()}") //TODO("doesn't apply permanently")
Toast.makeText(activity, "\"$course\" ${if (remove) "aus Filterliste entfernt" else "zu Filterliste hinzugefügt"}", Toast.LENGTH_SHORT).show()
}
The Logcat output looks like this:
RecyclerViewAdapter: Committed changed prefs: true
In the documentation the following is written:
Returns true if the new values were successfully written to persistent storage.
Thus, I would assume that the changes are written to the persistent storage and when requesting the SharedPreference in the same app process, the changes are there.
However, if I restart the app, the SharedPreference has its original value again and by checking the file where the SharedPreferences are stored (/data/data/[AppID]/shared_prefs/[AppID]_preferences.xml
) I was able to confirm that the changes were never written to persistent storage which contradicts what's written in the documentation.
Has anyone encountered this issue? What is causing this? How can I fix it?