如果要将List对象存储在SharedPreference中,请使用gson库。它将用于将列表对象转换为json格式,并将该json字符串存储到sharedPref中。
首先将此行包含在gradle文件中(应用级别)
编译’com.google.pre.gson:gson:2.4’
下面的代码是将类型设置为列表
Type listType = new TypeToken<List<String>>(){}.getType();Gson gson = new Gson();现在创建列表对象并使用gson对象并将其转换为json字符串格式
List<String> myList = new ArrayList<>();//add elements in myList objectString jsonFormat = gson.toJson(myList,listType); //adding to sharedPref editor.put("list",jsonFormat).apply();现在从sharedPref获取值,并将json字符串转换回List对象。
//this line will get the json string from sharedPref and will converted into object of type list(specified in listType object) List<String> list = gson.fromJson(sharedPref.get("list",""),listType); //now modify the list object as par your requirement and again do the same step of converting that list object into jsonFormat.


