0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SharedPreferencesで保存できる型・できない型まとめ

Posted at

Androidのデータ保存方法としてSharedPreferencesが利用できる。保存できるデータ型には決まりがあり、保存できる型とできない型の保存方法メモする。

保存できる型

SharedPreferencesで保存できるのは以下の一覧です。

val prefs = context.getSharedPreferences("sample_preferences", Context.MODE_PRIVATE)
val editor = prefs.edit()

editor.putString("string", "Hello World")
editor.putInt("int", 123)
editor.putLong("long", 123456789L)
editor.putFloat("float", 12.34f)
editor.putBoolean("boolean", true)
editor.putStringSet("string_set", setOf("Apple", "Banana"))

editor.apply()

上記データは問題なく保存できます。

保存できない型

下記の型は直接保存できません。

  • data class
  • List / Map
  • Bitmap
  • カスタムオブジェクト全般
data class User(val name: String, val age: Int)

val user = User("Alice", 20)
editor.putString("user", user)  // コンパイルエラーになる

これらはコンパイルエラーになります。

オブジェクトを保存したい場合の対処法

カスタムクラスや List/Map を保存したい場合は、JSON に変換して String とすれば保存できます。

val gson = Gson()
val userJson = gson.toJson(user)

editor.putString("user_json", userJson)
editor.apply()

読み込み法方

val json = prefs.getString("user_json", null)
val user: User? = gson.fromJson(json, User::class.java)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?