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?


当前回答

嘿,朋友们,我没有使用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);
 }

我希望这对你有帮助…

其他回答

为什么不把数组列表放在应用程序类上呢?它只有在应用被杀死时才会被销毁,所以,只要应用可用,它就会一直存在。

别忘了实现Serializable:

Class dataBean implements Serializable{
 public String name;
}
ArrayList<dataBean> dataBeanArrayList = new ArrayList();

https://stackoverflow.com/a/7635154/4639974

你可以使用Gson库保存字符串和自定义数组列表。

首先你需要创建一个函数来保存数组列表到SharedPreferences。

public void saveListInLocal(ArrayList<String> list, String key) {

        SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!

    }

你需要创建一个函数来从SharedPreferences获取数组列表。

public ArrayList<String> getListFromLocal(String key)
{
    SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);

}

如何调用保存和检索数组列表函数。

ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());

不要忘记在你的应用级别build.gradle中添加gson库。

实现“com.google.code.gson: gson: 2.8.2”

您可以将其转换为JSON字符串,并将字符串存储在SharedPreferences中。

在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类