gpt4 book ai didi

android - 将 SparseBooleanArray 保存到 SharedPreferences

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:17 26 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用 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();
}

读取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;
}

并像这样使用:

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

关于android - 将 SparseBooleanArray 保存到 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25050746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com