Android|Android SharedPreferences保存集合(List类型)

【Android|Android SharedPreferences保存集合(List类型)】安卓项目中会经常遇到使用SharedPreferences的情况,如果要保存的类型是List,可以这样实现:
1.定义MessageModel .java

public class MessageModel implements Serializable{ private String name; private String title; private String body; public String getName() { return name; }public void setName(String name) { this.name = name; }public String getTitle() { return title; }public void setTitle(String title) { this.title = title; }public String getBody() { return body; }public void setBody(String body) { this.body = body; } }

2.集合中添加数据并保存:
List namelist = new ArrayList<>(); MessageModel messageModel = new MessageModel(); messageModel.setName(name.getText().toString()); messageModel.setTitle(title.getText().toString()); messageModel.setBody(body.getText().toString()); namelist.add(messageModel); SharedPreferences sp = mBaseActivity.getSharedPreferences("SP_NewUserModel_List", Activity.MODE_PRIVATE); //创建sp对象 Gson gson = new Gson(); String jsonStr=gson.toJson(namelist); //将List转换成Json SharedPreferences.Editor editor = sp.edit() ; editor.putString("KEY_NewUserModel_LIST_DATA", jsonStr) ; //存入json串 editor.commit() ; //提交

3.读取数据
SharedPreferences sp = mBaseActivity.getSharedPreferences("SP_NewUserModel_List",Activity.MODE_PRIVATE); //创建sp对象,如果有key为"SP_PEOPLE"的sp就取出 String peopleListJson = sp.getString("KEY_NewUserModel_LIST_DATA",""); //取出key为"KEY_PEOPLE_DATA"的值,如果值为空,则将第二个参数作为默认值赋值 if(peopleListJson!="")//防空判断 { Gson gson = new Gson(); namelist = gson.fromJson(peopleListJson, new TypeToken>() {}.getType()); //将json字符串转换成List集合 }

    推荐阅读