Skip to content

Instantly share code, notes, and snippets.

@damianflannery
Created July 3, 2013 13:26
Show Gist options
  • Save damianflannery/5917828 to your computer and use it in GitHub Desktop.
Save damianflannery/5917828 to your computer and use it in GitHub Desktop.
Preferences.putStringSet() does not exist in Gingerbread so you can use this class below as a substitute if you need to target below Android v3.0 (Honeycomb)
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
public class JSONSharedPreferences {
private static final String PREFIX = "json";
public static void saveJSONObject(SharedPreferences prefs, String key, JSONObject object) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
editor.commit();
}
public static void saveJSONArray(SharedPreferences prefs, String key, JSONArray array) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
editor.commit();
}
public static JSONObject loadJSONObject(SharedPreferences prefs, String key) throws JSONException {
return new JSONObject(prefs.getString(JSONSharedPreferences.PREFIX+key, "{}"));
}
public static JSONArray loadJSONArray(SharedPreferences prefs, String key) throws JSONException {
return new JSONArray(prefs.getString(JSONSharedPreferences.PREFIX+key, "[]"));
}
public static void remove(SharedPreferences prefs, String key) {
if (prefs.contains(JSONSharedPreferences.PREFIX+key)) {
SharedPreferences.Editor editor = prefs.edit();
editor.remove(JSONSharedPreferences.PREFIX+key);
editor.commit();
}
}
}
//Below, the code to use putStringSet is commented out. Alternative JSONSharedPreferences is used instead
//Set<String> trainers = new TreeSet<String>();
JSONArray jTrainers = new JSONArray();
List<FilteredWorkoutVideo> videos = getAllFilteredVideos(prefs);
for (FilteredWorkoutVideo video : videos) {
//trainers.add(video.getTrainerName());
jTrainers.put(video.getTrainerName());
}
//e = prefs.edit();
//e.putStringSet(Constants.KEY_ALL_TRAINERS, trainers);
//e.apply();
JSONSharedPreferences.saveJSONArray(prefs, Constants.KEY_ALL_TRAINERS, jTrainers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment