kotlin SharedPreferences Generic MutableList 읽기, 쓰기.
https://stackoverflow.com/questions/7361627/how-can-write-code-to-make-sharedpreferences-for-array-in-android
stackoverflow 에 올라온 코드를 참조해 제네릭하게 만들어 봤습니다.
사용법은 아래와 같습니다.
val sharedPref = getSharedPreferences("config", MODE_PRIVATE)
setArrayPref<String>(sharedPref, "testList ", <<inList>> )
val testList = getArrayPref<String>(sharedPref, "testList")
fun <T> setArrayPref(prefs: SharedPreferences, key: String, values: MutableList<T>) {
val editor = prefs.edit()
val jArray = JSONArray()
for (i in 0 until values.size) {
jArray.put(values[i])
}
if (values.isNotEmpty()) {
editor.putString(key, jArray.toString())
} else {
editor.putString(key, null)
}
editor.commit()
}
fun <T> getArrayPref(prefs: SharedPreferences, key: String): MutableList<T> {
val json = prefs.getString(key, null)
val list = mutableListOf<T>()
if (json != null) {
try {
val a = JSONArray(json)
for (i in 0 until a.length()) {
val str = a.optString(i) as? T
if (str != null) {
list.add(str)
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
}
return list
}
댓글
댓글 쓰기