Save ArrayList to SharedPreferences

前端 未结 30 3545
野的像风
野的像风 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<String> set = myScores.getStringSet("key", null);
    
    //Set the values
    Set<String> set = new HashSet<String>();
    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<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();
    }
    

    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<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();
      }
    }
    

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

    0 讨论(0)
  • 2020-11-21 05:15
        public  void saveUserName(Context con,String username)
        {
            try
            {
                usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
                usernameEditor = usernameSharedPreferences.edit();
                usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1)); 
                int size=USERNAME.size();//USERNAME is arrayList
                usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
                usernameEditor.commit();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
    
        }
        public void loadUserName(Context con)
        {  
            try
            {
                usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
                size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
                USERNAME.clear();
                for(int i=0;i<size;i++)
                { 
                    String username1="";
                    username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
                    USERNAME.add(username1);
                }
                usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
                username.setAdapter(usernameArrayAdapter);
                username.setThreshold(0);
    
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
  • 2020-11-21 05:16

    You can save String and custom array list using Gson library.

    =>First you need to create function to save array list to 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 !!!
    
        }
    

    => You need to create function to get array list from 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);
    
    }
    

    => How to call save and retrieve array list function.

    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());
    

    => Don't forgot to add gson library in you app level build.gradle.

    implementation 'com.google.code.gson:gson:2.8.2'

    0 讨论(0)
  • 2020-11-21 05:16

    You can use serialization or Gson library to convert list to string and vice versa and then save string in preferences.

    Using google's Gson library:

    //Converting list to string
    new Gson().toJson(list);
    
    //Converting string to list
    new Gson().fromJson(listString, CustomObjectsList.class);
    

    Using Java serialization:

    //Converting list to string
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(list);
    oos.flush();
    String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
    oos.close();
    bos.close();
    return string;
    
    //Converting string to list
    byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
    ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
    ObjectInputStream ois = new ObjectInputStream(bis);
    Object clone = ois.readObject();
    ois.close();
    bis.close();
    return (CustomObjectsList) clone;
    
    0 讨论(0)
  • 2020-11-21 05:19

    Also with Kotlin:

    fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
        putString(key, list?.joinToString(",") ?: "")
        return this
    }
    
    fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
        val value = getString(key, null)
        if (value.isNullOrBlank())
            return defValue
        return ArrayList (value.split(",").map { it.toInt() }) 
    }
    
    0 讨论(0)
  • 2020-11-21 05:19

    Use this custom class:

    public class SharedPreferencesUtil {
    
        public static void pushStringList(SharedPreferences sharedPref, 
                                          List<String> list, String uniqueListName) {
    
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt(uniqueListName + "_size", list.size());
    
            for (int i = 0; i < list.size(); i++) {
                editor.remove(uniqueListName + i);
                editor.putString(uniqueListName + i, list.get(i));
            }
            editor.apply();
        }
    
        public static List<String> pullStringList(SharedPreferences sharedPref, 
                                                  String uniqueListName) {
    
            List<String> result = new ArrayList<>();
            int size = sharedPref.getInt(uniqueListName + "_size", 0);
    
            for (int i = 0; i < size; i++) {
                result.add(sharedPref.getString(uniqueListName + i, null));
            }
            return result;
        }
    }
    

    How to use:

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
    List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));
    
    0 讨论(0)
提交回复
热议问题