Search code examples
androidperformancesharedpreferencesandroid-sqlitesparse-array

Save SparseBooleanArray to SharedPreferences


For my app, I need to save a simple SparseBooleanArray to memory and read it later. Is there any way to save it using SharedPreferences?

I considered using an SQLite database but it seemed overkill for something as simple as this. Some other answers I found on StackOverflow suggested using GSON for saving it as a String but I need to keep this app very light and fast in file size. Is there any way of achieving this without relying on a third party library and while maintaining good performance?


Solution

  • You can use the power of JSON to save in the shared preferences for any type of object

    For example SparseIntArray Save items like Json string

    public static void saveArrayPref(Context context, String prefKey, SparseIntArray intDict) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray json = new JSONArray();
        StringBuffer data = new StringBuffer().append("[");
        for(int i = 0; i < intDict.size(); i++) {
            data.append("{")
                    .append("\"key\": ")
                    .append(intDict.keyAt(i)).append(",")
                    .append("\"order\": ")
                    .append(intDict.valueAt(i))
                    .append("},");
            json.put(data);
        }
        data.append("]");
        editor.putString(prefKey, intDict.size() == 0 ? null : data.toString());
        editor.commit();
    }
    

    and read json string

    public static SparseIntArray getArrayPref(Context context, String prefKey) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String json = prefs.getString(prefKey, null);
        SparseIntArray intDict = new SparseIntArray();
        if (json != null) {
            try {
                JSONArray jsonArray = new JSONArray(json);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject item = jsonArray.getJSONObject(i);
                    intDict.put(item.getInt("key"), item.getInt("order"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return intDict;
    }
    

    and use like this:

        SparseIntArray myKeyList = new SparseIntArray(); 
        ...
        //write list
        saveArrayPref(getApplicationContext(),"MyList", myKeyList);
        ...
        //read list
        myKeyList = getArrayPref(getApplicationContext(), "MyList");