码迷,mamicode.com
首页 > 移动开发 > 详细

Android保存ArrayList至SharedPreferences

时间:2016-12-12 20:04:10      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:tty   editor   print   mode   add   on()   mod   edit   sub   

保存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

标签:tty   editor   print   mode   add   on()   mod   edit   sub   

原文地址:http://www.cnblogs.com/ldq2016/p/6165513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!