Android儲存ArrayList至SharedPreferences

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.