Last active
July 8, 2018 11:32
-
-
Save shreeshga/5398506 to your computer and use it in GitHub Desktop.
Android setSringSet() / getStringSet() with compatibility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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