Shared preferences introduced a getStringSet
and putStringSet
methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.
Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:
package com.example.utils;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
public class JSONSharedPreferences {
private static final String PREFIX = "json";
public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
editor.commit();
}
public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
editor.commit();
}
public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
}
public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
}
public static void remove(Context c, String prefName, String key) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
SharedPreferences.Editor editor = settings.edit();
editor.remove(JSONSharedPreferences.PREFIX+key);
editor.commit();
}
}
}
Now you can save any collection in shared preferences with this five methods. Working with JSONObject
and JSONArray
is very easy. You can use JSONArray (Collection copyFrom)
public constructor to make a JSONArray
out of any Java collection and use JSONArray
's get
methods to access the elements.
There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.