LoginSignup
9
9

More than 5 years have passed since last update.

SharedPrefarenceで好きな型の値を保存する

Posted at

はじめに

値を簡単に保存できるsharedprefarencesというのがあります。けれどこいつは元々存在する特定の型の値しか保存できないので不便です。
今回はどんな型でも保存できる方法をメモします。

方法

基本的にはGsonを使って保存したいオブジェクトをJSONに変換して、それをString型のものとしてsharedprefarencesで保存するだけ

使ったライブラリ
Gson

読み込み
SharedPreferences preferences = getActivity().getSharedPreferences("key", Activity.MODE_PRIVATE);
Gson gson = new Gson();
ArrayList<MyData> mydata = gson.fromJson(preferences.getString("topic",""), new TypeToken<List<MyData>>(){}.getType());
書き込み
SharedPreferences preferences = getActivity().getSharedPreferences("key", Activity.MODE_PRIVATE);
Gson gson = new Gson();
preferences.edit().putString("topic", gson.toJson(mydata)).commit();

参考サイト

9
9
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
9
9