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を良きに利用する