SharedPreferencesの読み書き

 

 

以下のようにしてActivityに書けばそれぞれできる。


// 読み出し
SharedPreferences preferences = getSharedPreferences("key", Activity.MODE_PRIVATE);
Gson gson = new Gson();
HashMap<String, String> mydata = gson.fromJson(preferences.getString("ok",""), new TypeToken<HashMap<String, String>>(){}.getType());
if(mydata!=null) {
for(Map.Entry e : mydata.entrySet()) {
Log.d("OKOK","キー : " + e.getKey() + " バリュー : " + e.getValue());
}
}


// 保存
SharedPreferences preferences = getSharedPreferences("key", Activity.MODE_PRIVATE);
Map<String, String> mydata = new HashMap<String, String>();
mydata.put("ねこ", "にゃあ!");
mydata.put("いぬ", "わん!");
Gson gson = new Gson();
preferences.edit().putString("ok", gson.toJson(mydata)).commit();