Android SharedPreferences保存LIST

平時我們碰到的大多數是保護用戶名,密碼這些數據,數量比較少,而保存ArrayList至SharedPreferences 比較少,下面我們來看看如何保存的。

  1. 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());
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,065評論 25 708
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,754評論 18 399
  • 本文出自 Eddy Wiki ,轉載請注明出處:http://eddy.wiki/interview-java.h...
    eddy_wiki閱讀 1,182評論 0 16
  • 01. 在連著很長一段時間讀書后,我有意識地放慢了閱讀的腳步。最近一兩個月,我看的書少了,寫的東西更少,學習的速度...
    淡之閱讀 667評論 13 31
  • 今天和大家分享的書籍是,《超級時間整理術,每天多出一小時》 001 當我們總說時間不夠用的時候,先從自身尋找問題。...
    愛冒險的兔子醬閱讀 270評論 0 0