首页 > 代码库 > Android保存ArrayList至SharedPreferences

Android保存ArrayList至SharedPreferences

保存ArrayList至SharedPreferences
其中ArrayList中每个元素为String

List<String> environmentList = new ArrayList<String>();
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();

 

对应的取出操作为:

List<String> environmentList = new ArrayList<String>();
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中

List<CoordinateAlterSample> alterSamples = new ArrayList<CoordinateAlterSample>();
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);
String json = preferences.getString("alterSampleJson", null);
if (json != null)
{
    Gson gson = new Gson();
    Type type = new TypeToken<List<CoordinateAlterSample>>(){}.getType();
    List<CoordinateAlterSample> alterSamples = new ArrayList<CoordinateAlterSample>();
    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());
    }
}

Android保存ArrayList至SharedPreferences