Skip to content

Instantly share code, notes, and snippets.

@javimar
Created March 23, 2020 12:31
Show Gist options
  • Save javimar/4ad616f7efbc7fe30b2b15bf58b94bb2 to your computer and use it in GitHub Desktop.
Save javimar/4ad616f7efbc7fe30b2b15bf58b94bb2 to your computer and use it in GitHub Desktop.
Correct way to update a Set containing widgets Ids in SharedPreferences.
public static void updateSetInPreferences(Context context, int appWidgetId, String key, String action)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
Set<String> storedSet, in;
switch(action)
{
case ACTION_ADD_APP_WIDGET_ID:
storedSet = prefs.getStringSet(key, new HashSet<>());
in = new HashSet<>(storedSet);
in.add(String.valueOf(appWidgetId));
editor.putStringSet(key, in);
break;
case ACTION_REMOVE_APP_WIDGET_ID:
storedSet = prefs.getStringSet(key, new HashSet<>()); // Access it
in = new HashSet<>(storedSet);
in.remove(String.valueOf(appWidgetId));
editor.putStringSet(key, in); // Put it back in Prefs
break;
}
editor.apply();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment