▣ Model
data class Person(val name: String, val age: Int)
▣ Read
val preferences = getSharedPreferences("pref", Context.MODE_PRIVATE)
val jsonData = preferences.getString("person", "")
val gson = Gson()
val token: TypeToken<MutableList<Person>> = object : TypeToken<MutableList<Person>>(){}
val list: MutableList<Person>? = gson.fromJson(jsonData, token.type)
▣ Write
val preferences = getSharedPreferences("pref", Context.MODE_PRIVATE)
val jsonData = preferences.getString("person", "")
val gson = Gson()
val token: TypeToken<MutableList<Person>> = object : TypeToken<MutableList<Person>>(){}
val list: MutableList<Person>? = gson.fromJson(jsonData, token.type)
list.add(Person("Tom", 20))
list.add(Person("Harry", 25))
val editor = preferences.edit()
editor.putString("person", gson.toJson(list, token.type))
editor.apply()
'프로그래밍 > android' 카테고리의 다른 글
[Android 12] Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE (0) | 2021.11.18 |
---|---|
[android] 안드로이드 태블릿 구분하기 (feat. 코틀린) (0) | 2021.09.14 |
Android 11 Full Screen (0) | 2021.07.29 |
[android] Dp to Px, Px to Dp (0) | 2021.06.30 |
[kotlin] android EditText setMaxLength Programmatically (0) | 2021.06.30 |