将SparseBooleanArray保存到SharedPreferences

Pkm*_*mte 3 performance android sparse-array sharedpreferences android-sqlite

对于我的应用程序,我需要将一个简单的SparseBooleanArray保存到内存中,然后再读取。有什么方法可以使用SharedPreferences保存它吗?

我考虑过使用SQLite数据库,但是对于像这样简单的事情来说似乎过于矫kill过正。我在StackOverflow上发现的其他一些答案建议使用GSON将其另存为字符串,但我需要使该应用程序保持非常轻便且文件大小快速。有什么方法可以在不依赖第三方库的情况下保持良好性能的同时实现这一目标?

mis*_*Man 5

您可以使用JSON的功能保存任何类型对象的共享首选项

例如SparseIntArray保存项目,例如Json字符串

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();
}
Run Code Online (Sandbox Code Playgroud)

并读取json字符串

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;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用:

    SparseIntArray myKeyList = new SparseIntArray(); 
    ...
    //write list
    saveArrayPref(getApplicationContext(),"MyList", myKeyList);
    ...
    //read list
    myKeyList = getArrayPref(getApplicationContext(), "MyList");
Run Code Online (Sandbox Code Playgroud)