I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?
当前回答
您还可以将数组列表转换为String并优先保存
private String convertToString(ArrayList<String> list) {
StringBuilder sb = new StringBuilder();
String delim = "";
for (String s : list)
{
sb.append(delim);
sb.append(s);;
delim = ",";
}
return sb.toString();
}
private ArrayList<String> convertToArray(String string) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
return list;
}
您可以使用convertToString方法将数组列表转换为字符串后保存它,并使用convertToArray方法检索字符串并将其转换为数组
在API 11之后,你可以直接保存设置到SharedPreferences !!:)
其他回答
使用Kotlin,对于简单的数组和列表,你可以这样做:
class MyPrefs(context: Context) {
val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
var listOfFloats: List<Float>
get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
}
然后轻松访问首选项:
MyPrefs(context).listOfFloats = ....
val list = MyPrefs(context).listOfFloats
最好的方法是使用GSON转换为JSOn字符串并保存此字符串到SharedPreference。 我还使用这种方式缓存响应。
还有Kotlin:
fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
putString(key, list?.joinToString(",") ?: "")
return this
}
fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
val value = getString(key, null)
if (value.isNullOrBlank())
return defValue
return ArrayList (value.split(",").map { it.toInt() })
}
以防有人需要保存列表的列表,即list < list < String > >。我是这样做的:
序列化
Gson gson = new Gson();
// Save the size of the array
sharedPreferencesEditor.putInt("ArraySize", myArray.size());
for (int i=0; i<myArray.size(); i++) {
String key = "Array"+i;
String json = gson.toJson(myArray.get(i));
sharedPreferencesEditor.putString(key, json);
}
sharedPreferencesEditor.commit();
反序列化
// Get the size of the array to be deserialized. In my case, the default number should be 3
int arraySize = sharedPreferences.getInt("ArraySize",3);
myArray = new ArrayList<List<String>>();
for (int i=0; i<arraySize; i++) {
String key = "Array"+i;
String json = sharedPreferences.getString(key, null);
List<String> arrayTemp= gson.fromJson(json, List.class);
myArray.add(arrayTemp);
}
// My array may also include components with empty strings.
// Gson makes them null values and it is not possible
// to deserialize them as empty strings.
// The following takes care of that:
for (int i=0; i<myArray.size();i++) {
if (myArray.get(i) == null) {
List<String> emptyComponent = new ArrayList<String>() {
{ add(""); }
};
myArray.set(i,emptyComponent);
}
}
嘿,朋友们,我没有使用Gson库就得到了上述问题的解决方案。我在这里发布源代码。
1.变量声明,即
SharedPreferences shared;
ArrayList<String> arrPackage;
2.变量初始化,即
shared = getSharedPreferences("App_settings", MODE_PRIVATE);
// add values for your ArrayList any where...
arrPackage = new ArrayList<>();
3.使用packagesharedPreferences()将值存储到sharedPreference:
private void packagesharedPreferences() {
SharedPreferences.Editor editor = shared.edit();
Set<String> set = new HashSet<String>();
set.addAll(arrPackage);
editor.putStringSet("DATE_LIST", set);
editor.apply();
Log.d("storesharedPreferences",""+set);
}
4.使用retriveSharedValue()检索sharedPreference的值:
private void retriveSharedValue() {
Set<String> set = shared.getStringSet("DATE_LIST", null);
arrPackage.addAll(set);
Log.d("retrivesharedPreferences",""+set);
}
我希望这对你有帮助…
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?