Save ArrayList to SharedPreferences

前端 未结 30 3563
野的像风
野的像风 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:19

    Use this custom class:

    public class SharedPreferencesUtil {
    
        public static void pushStringList(SharedPreferences sharedPref, 
                                          List 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 pullStringList(SharedPreferences sharedPref, 
                                                  String uniqueListName) {
    
            List 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 list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));
    

提交回复
热议问题