平时我们碰到的大多数是保护用户名,密码这些数据,数量比较少,而保存ArrayList至SharedPreferences 比较少,下面我们来看看如何保存的。
- ArrayList中每个元素为String:
List<String> environmentList = new ArrayList<String>();
SharedPreferences.Editor editor = getSharedPreferences("ReasonDataList", MODE_PRIVATE).edit();
editor.putInt("ReasonNums", environmentList.size());
for (int i = 0; i < environmentList.size(); i++)
{
editor.putString("item_"+i, environmentList.get(i));
}
editor.commit();
对应的取出操作为
List<String> environmentList = new ArrayList<String>();
SharedPreferences preferDataList = getSharedPreferences("ReasonDataList", MODE_PRIVATE);
int environNums = preferDataList.getInt("ReasonNums", 0);
for (int i = 0; i < environNums; i++)
{
String environItem = preferDataList.getString("item_"+i, null);
environmentList.add(environItem);
}
2.list的每个元素为自定义对象
首先将自定义对象序列化
public class DemoBean implements Serializable {
private double x;
private double y;
private String name;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
其次,将list转为json,即可保存到SharedPreferences中
List<DemoBean > bean= new ArrayList<DemoBean >();
SharedPreferences.Editor editor = getSharedPreferences("DemoBeansList", MODE_PRIVATE).edit();
Gson gson = new Gson();
String json = gson.toJson(bean);
Log.d(TAG, "saved json is "+ json);
editor.putString("demoBeanJson", json);
editor.commit();
对应的取出操作为:
SharedPreferences preferences = getSharedPreferences("DemoBeansList", MODE_PRIVATE);
String json = preferences.getString("demoBeanJson", null);
if (json != null)
{
Gson gson = new Gson();
Type type = new TypeToken<List<CoordinateAlterSample>>(){}.getType();
List<DemoBean > alterSamples = new ArrayList<DemoBean >();
alterSamples = gson.fromJson(json, type);
for(int i = 0; i < alterSamples.size(); i++)
{
Log.d(TAG, alterSamples.get(i).getName()+":" + alterSamples.get(i).getX() + "," + alterSamples.get(i).getY());
}
}