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?
当前回答
//Set the values
intent.putParcelableArrayListExtra("key",collection);
//Retrieve the values
ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");
其他回答
在SharedPreferences中保存数组:
public static boolean saveArray()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
/* sKey is an array */
mEdit1.putInt("Status_size", sKey.size());
for(int i=0;i<sKey.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, sKey.get(i));
}
return mEdit1.commit();
}
从SharedPreferences加载数组数据
public static void loadArray(Context mContext)
{
SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
sKey.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
sKey.add(mSharedPreference1.getString("Status_" + i, null));
}
}
在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类
正如@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();
下面的代码是公认的答案,为新手(我)多写几行,例如。说明了如何将set类型对象转换回arrayList,并提供了关于`之前操作的附加指导。putStringSet'和。getstringset '。(谢谢你邪恶)
// shared preferences
private SharedPreferences preferences;
private SharedPreferences.Editor nsuserdefaults;
// setup persistent data
preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);
nsuserdefaults = preferences.edit();
arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
//Retrieve followers from sharedPreferences
Set<String> set = preferences.getStringSet("following", null);
if (set == null) {
// lazy instantiate array
arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
} else {
// there is data from previous run
arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
}
// convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
Set<String> set = new HashSet<String>();
set.addAll(arrayOfMemberUrlsUserIsFollowing);
nsuserdefaults.putStringSet("following", set);
nsuserdefaults.commit();
/**
* 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集成无效键散列