LoginSignup
27
30

More than 5 years have passed since last update.

sharedPreferenceにArraylistのデータを保存する

Posted at

AndroidのsharedPreferenceに保存できるのはint,long,String,boolean,setなどがあります。
が、場合によっては色々な型のArraylistを保存したい場合もあると思います。その方法について書きました。

やりかた

JSONArrayに保存し、シリアライズ化します。

データの保存


JSONArray array = new JSONArray();
for (int i = 0, length = list.size(); i < length; i++) {
    try {
        array.put(i, list.get(i));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Editor editor = getApplicationContext().getSharedPreferences("shared_preference", Context.MODE_PRIVATE).edit();

editor.putString("list", array.toString());  //key名を"list"としてシリアライズ化したデータを保存
editor.commit();

データの取り出し

他の値が保存されている場合も考慮して、一旦Bundleにプリファレンスのデータを移すのがミソです。


String list;
Bundle bundle = new Bundle();  //保存用のバンドル
Map<String, ?> prefKV = getApplicationContext().getSharedPreferences("shared_preference", Context.MODE_PRIVATE).getAll();
Set<String> keys = prefKV.keySet();
    for(String key : keys){
        Object value = prefKV.get(key);
        if(value instanceof String){
              bundle.putString(key, (String) value);  
        }else if(value instanceof Integer){
        // …略
        }
    }

String stringList = bundle.getString("list");  //key名が"list"のものを取り出す
ArrayList<String> list = new ArrayList<String>();
    try {
        JSONArray array = new JSONArray(stringList);
        for(int i = 0, length = array.length(); i < length; i++){
            list.add(array.optString(i));
        }
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

//あとはlistを良きに利用する
27
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
30