Save ArrayList to SharedPreferences

前端 未结 30 3649
野的像风
野的像风 2020-11-21 04:43

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

30条回答
  •  旧巷少年郎
    2020-11-21 05:13

    After API 11 the SharedPreferences Editor accepts Sets. You could convert your List into a HashSet or something similar and store it like that. When you read it back, convert it into an ArrayList, sort it if needed and you're good to go.

    //Retrieve the values
    Set set = myScores.getStringSet("key", null);
    
    //Set the values
    Set set = new HashSet();
    set.addAll(listOfExistingScores);
    scoreEditor.putStringSet("key", set);
    scoreEditor.commit();
    

    You can also serialize your ArrayList and then save/read it to/from SharedPreferences. Below is the solution:

    EDIT:
    Ok, below is the solution to save ArrayList as a serialized object to SharedPreferences and then read it from SharedPreferences.

    Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it's simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.

    In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method:

    public void addTask(Task t) {
      if (null == currentTasks) {
        currentTasks = new ArrayList();
      }
      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();
    }
    

    Similarly we have to retrieve the list of tasks from the preference in the onCreate() method:

    public void onCreate() {
      super.onCreate();
      if (null == currentTasks) {
        currentTasks = new ArrayList();
      }
     
      // load tasks from preference
      SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
     
      try {
        currentTasks = (ArrayList) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList())));
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
    

    You can get the ObjectSerializer class from the Apache Pig project ObjectSerializer.java

提交回复
热议问题