ArrayListをJSONに変換して保存する
ArrayList
サイズが可変なのでJSONにしてしまったときのコード。
保存処理
private static void saveItems(Context context, String key, ArrayList<String> items) {
// List<String> -> JSONに変換
String json = new JSONArray(items).toString();
// Preferencesに保存
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
pref.edit().putString(key, json).commit();
}
読出処理
private static ArrayList<String> loadItems(Context context, String key) {
ArrayList<String> items = new ArrayList<String>();
// Preferencesから呼び出し
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String json = pref.getString(key, "");
if(!TextUtils.isEmpty(json)) {
// JSON -> List<String>に変換
try {
JSONArray arr = new JSONArray(json);
for(int i=0; i < arr.length(); i++) {
items.add(arr.getString(i));
}
} catch (JSONException e) {
}
}
return items;
}
Comments are currently closed.