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
}


댓글

이 블로그의 인기 게시물

파이썬 vscode에서 자동 코드 정렬. Formatter.

Unity3D git 저장소에 올릴때 필요없는 파일 제외하기. gitignore

플러터(flutter) 개발 참고 사이트들.