Save ArrayList to SharedPreferences

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

    You can also convert the arraylist into a String and save that in preference

    private String convertToString(ArrayList list) {
    
                StringBuilder sb = new StringBuilder();
                String delim = "";
                for (String s : list)
                {
                    sb.append(delim);
                    sb.append(s);;
                    delim = ",";
                }
                return sb.toString();
            }
    
    private ArrayList convertToArray(String string) {
    
                ArrayList list = new ArrayList(Arrays.asList(string.split(",")));
                return list;
            }
    

    You can save the Arraylist after converting it to string using convertToString method and retrieve the string and convert it to array using convertToArray

    After API 11 you can save set directly to SharedPreferences though !!! :)

提交回复
热议问题