Android SharedPreferences 存储List类型数据

保存ArrayList至SharedPreferences

其中ArrayList中每个元素为String:

ListenvironmentList = new ArrayList();

SharedPreferences.Editor editor = getSharedPreferences("EnvironDataList", MODE_PRIVATE).edit();

editor.putInt("EnvironNums", environmentList.size());

for (int i = 0; i < environmentList.size(); i++)

{  editor.putString("item_"+i, environmentList.get(i));

}

editor.commit();

对应的取出操作为:

ListenvironmentList = new ArrayList();

SharedPreferences preferDataList = getSharedPreferences("EnvironDataList", MODE_PRIVATE);

int environNums = preferDataList.getInt("EnvironNums", 0);

for (int i = 0; i < environNums; i++)

{

String environItem = preferDataList.getString("item_"+i, null);

environmentList.add(environItem);

}


保存ArrayList至SharedPreferences,其中list的每个元素为自定义对象

1 首先将自定义对象序列化

public class CoordinateAlterSample 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中:

ListalterSamples = new ArrayList();

SharedPreferences.Editor editor = getSharedPreferences("AlterSamplesList", MODE_PRIVATE).edit();

Gson gson = new Gson();

String json = gson.toJson(alterSamples);

Log.d(TAG, "saved json is "+ json);

editor.putString("alterSampleJson", json);

editor.commit();

对应的取出操作为:

SharedPreferences preferences=getSharedPreferences("AlterSamplesList", MODE_PRIVATE);

Stringjson=preferences.getString("alterSampleJson",null);

if(json!=null){

Gson gson=newGson();Typetype=newTypeToken>(){}.

getType();

ListalterSamples=newArrayList();

alterSamples=gson.fromJson(json,type);

for(int i=0; i

{Log.d(TAG, alterSamples.get(i).getName()+":"+alterSamples.get(i).getX()+","+alterSamples.get(i).getY());

}

}

你可能感兴趣的:(Android SharedPreferences 存储List类型数据)