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?
当前回答
别忘了实现Serializable:
Class dataBean implements Serializable{
public String name;
}
ArrayList<dataBean> dataBeanArrayList = new ArrayList();
https://stackoverflow.com/a/7635154/4639974
其他回答
您可以将其转换为JSON字符串,并将字符串存储在SharedPreferences中。
在SharedPreferences中使用getStringSet和putStringSet非常简单,但在我的情况下,我必须在向Set中添加任何东西之前复制Set对象。否则,Set将不会被保存,如果我的应用程序是强制关闭。可能是因为下面API中的注释。(如果应用程序被返回按钮关闭,则保存)。
注意,您不能修改此调用返回的set实例。如果这样做,则无法保证存储数据的一致性,也无法保证修改实例的能力。 http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
Set<String> outSet = prefs.getStringSet("key", new HashSet<String>());
Set<String> workingSet = new HashSet<String>(outSet);
workingSet.add("Another String");
editor.putStringSet("key", workingSet);
editor.commit();
正如@nirav所说,最好的解决方案是使用Gson实用工具类将其作为json文本存储在sharedpreferences中。下面是示例代码:
//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class); //EDIT: gso to gson
//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();
public class VcareSharedPreference {
private static VcareSharedPreference sharePref = new VcareSharedPreference();
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
private VcareSharedPreference() {
}
public static VcareSharedPreference getInstance(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
return sharePref;
}
public void save(String KEY, String text) {
editor.putString(KEY, text);
editor.commit();
}
public String getValue(String PREFKEY) {
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
text = sharedPreferences.getString(PREFKEY, null);
return text;
}
public void removeValue(String KEY) {
editor.remove(KEY);
editor.commit();
}
public void clearAll() {
editor.clear();
editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
Gson gson = new Gson();
String json = gson.toJson(modelCourses);
editor.putString(key, json);
editor.apply();
}
public ArrayList<ModelWelcome> getArray(String key) {
Gson gson = new Gson();
String json = sharedPreferences.getString(key, null);
Type type = new TypeToken<ArrayList<ModelWelcome>>() {
}.getType();
return gson.fromJson(json, type);}}
在API 11之后,SharedPreferences Editor接受set。您可以将List转换为HashSet或类似的东西,并像这样存储它。当你把它读回来时,把它转换成一个数组列表,如果需要的话对它排序,你就可以开始了。
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
你也可以序列化你的数组列表,然后将它保存/读取到SharedPreferences。解决方案如下:
编辑: 下面是将ArrayList作为一个序列化对象保存到SharedPreferences的解决方案,然后从SharedPreferences中读取它。
因为API只支持在SharedPreferences中存储和检索字符串(在API 11之后,它更简单),我们必须序列化和反序列化ArrayList对象,它将任务列表变成一个字符串。
在TaskManagerApplication类的addTask()方法中,我们必须获取共享首选项的实例,然后使用putString()方法存储序列化的ArrayList:
public void addTask(Task t) {
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
currentTasks.add(t);
// save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}
类似地,我们必须从onCreate()方法中的首选项中检索任务列表:
public void onCreate() {
super.onCreate();
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
您可以从Apache Pig项目ObjectSerializer.java中获得ObjectSerializer类
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在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)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?