I am trying to write a string set to shared preferences and at first glance it appears to work. In other parts of the app I can access the shared preferences and read the string set correctly.
The problem comes when I leave the app. All the data from the shared preferences string set is lost and it returns an empty set again.
The fact that I can access it until the app is closed and reopened make me think that it is being stored in memory but not stored to disk.
I read a lot of the answers on here, tried changing between commit and apply but I don't know what is causing the issue.
The way I try to save it is:
- Retrieve the hashset from shared preference
- Add new string to the hashset
- Save the updated hashset in shared preference.
Here is the code:
public static void storeReminder (Context context, String reminderString){
// Get the set of reminder strings
SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
Set <String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
// Add the new reminder string to the reminder string set
remindersStringSet.add(reminderString);
// Save the reminder string set now that the new reminder string has been added
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet(context.getResources().getString(R.string.reminders_hashset_key), remindersStringSet);
editor.commit();
}
And this is how I get the the stored hashset in other part of the app:
// Get the set of reminder strings
SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
Set<String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
Thanks in advance for your help