Skip to content

Instantly share code, notes, and snippets.

@KonradIT
Forked from shreeshga/Utilities.java
Created July 8, 2018 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KonradIT/c03b1310f77dc1a9d647b989945be9e0 to your computer and use it in GitHub Desktop.
Save KonradIT/c03b1310f77dc1a9d647b989945be9e0 to your computer and use it in GitHub Desktop.
Android setSringSet() / getStringSet() with compatibility
public static void setPersistentObjectSet(Context context, String key, String o) {
if (initStore(context)) {
synchronized (_store) {
SharedPreferences.Editor editor = _store.edit();
if (o == null) {
editor.remove(key);
} else {
Set<String> vals = null;
if (VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
vals = _store.getStringSet(key, null);
} else {
String s = _store.getString(key, null);
if(s != null)
vals = new HashSet<String>(Arrays.asList(s.split(",")));
}
if (vals == null) vals = new HashSet<String>();
vals.add(o);
if (VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
editor.putStringSet(key, vals);
} else {
editor.putString(key, join(vals, ","));
}
}
editor.commit();
}
}
}
public static Set<String> getPersistentObjectSet(Context context, String key) {
if (initStore(context)) {
synchronized (_store) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return _store.getStringSet(key, null);
} else {
String s = _store.getString(key, null);
if (s != null) return new HashSet<String>(Arrays.asList(s.split(",")));
else return null;
}
}
} return null;
}
public static String join(Set<String> set, String delim) {
StringBuilder sb = new StringBuilder();
String loopDelim = "";
for (String s : set) {
sb.append(loopDelim);
sb.append(s);
loopDelim = delim;
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment