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?
当前回答
使用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
其他回答
这就是你的完美解决方案。试一试,
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
以上答案都是正确的。:)我自己就用了其中一个。然而,当我读到这个问题时,我发现这篇文章实际上是在谈论一个不同的场景,如果我没有弄错的话。
"我需要这个数组一直存在即使用户离开了活动然后想要在稍后的时间回来"
实际上,他希望数据一直存储到应用程序打开为止,而不管用户在应用程序中更换屏幕。
“然而,我不需要阵列可用后,应用程序已完全关闭”
但是一旦应用程序关闭,数据就不应该被保存。因此,我觉得使用SharedPreferences并不是最优的方式。
对于这个需求,我们可以创建一个扩展Application类的类。
public class MyApp extends Application {
//Pardon me for using global ;)
private ArrayList<CustomObject> globalArray;
public void setGlobalArrayOfCustomObjects(ArrayList<CustomObject> newArray){
globalArray = newArray;
}
public ArrayList<CustomObject> getGlobalArrayOfCustomObjects(){
return globalArray;
}
}
通过setter和getter,可以从应用程序中的任何地方访问ArrayList。最好的部分是一旦应用程序关闭,我们不必担心数据被存储。:)
//Set the values
intent.putParcelableArrayListExtra("key",collection);
//Retrieve the values
ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");
使用Kotlin和GSON:
fun <T> SharedPreferences.writeList(gson: Gson, key: String, data: List<T>) {
val json = gson.toJson(data)
edit { putString(key, json) }
}
inline fun <reified T> SharedPreferences.readList(gson: Gson, key: String): List<T> {
val json = getString(key, "[]") ?: "[]"
val type = object : TypeToken<List<T>>() {}.type
return try {
gson.fromJson(json, type)
} catch(e: JsonSyntaxException) {
emptyList()
}
}
/**
* Save and get ArrayList in SharedPreference
*/
JAVA:
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
科特林
fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val editor: Editor = prefs.edit()
val gson = Gson()
val json: String = gson.toJson(list)
editor.putString(key, json)
editor.apply()
}
fun getArrayList(key: String?): java.util.ArrayList<String?>? {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val gson = Gson()
val json: String = prefs.getString(key, null)
val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
return gson.fromJson(json, type)
}
推荐文章
- Manifest合并失败:uses-sdk:minSdkVersion 14
- 为什么Android工作室说“等待调试器”如果我不调试?
- 如何检查我的EditText字段是否为空?
- Android从图库中选择图像
- 后台任务,进度对话框,方向改变-有任何100%工作的解决方案吗?
- Android:垂直对齐多行EditText(文本区域)
- Android无尽列表
- Android room persistent: AppDatabase_Impl不存在
- 错误:执行失败的任务':app:compileDebugKotlin'。>编译错误。详细信息请参见日志
- 在Android中使用URI生成器或使用变量创建URL
- 缩放图像以填充ImageView宽度并保持纵横比
- 列表视图的自定义适配器
- 在Android中设置TextView span的颜色
- 如何以编程方式在RelativeLayout中布局视图?
- Android Facebook集成无效键散列