본문 바로가기
안드로이드

SharedPreferences 똑똑하게 사용하기.

by 아카이sun 2019. 8. 29.

예전에 우리가 자바에서 사용하던 방법

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("key","value");
editor.apply();

 

코틀린으로 사용하면?

private val pref = PreferenceManager.getDefaultSharedPreferences(context)

    @Suppress("IMPLICIT_CAST_TO_ANY")
    fun<T> get(key: String, defaultValue: T): T {
        return when (defaultValue) {
            is String -> pref.getString(key, defaultValue)
            is Int -> pref.getInt(key, defaultValue)
            is Boolean -> pref.getBoolean(key, defaultValue)
            is Float -> pref.getFloat(key, defaultValue)
            is Long -> pref.getLong(key, defaultValue)
            else -> throw UnsupportedOperationException("Not yet implemented")
        } as T
    }

 

Config같은 것을 저장해야 하는데 DB는 번거롭다.

 

gson을 사용하여 json형태로 저장

val res = Gson().toJson(jsonText)
pref.save(key, res)

 

gson을 이용하여 클래스를 꺼내기 

fun getConfig(sharedPref: SharedPreferenceProvider, key: String) : Config {
    var res = sharedPref.get(key, "")
    val type = object : TypeToken<Config>() {}.type
    if(res.isEmpty()) {
    res = Link().toString()
    }
    return Gson().fromJson(res, type)
}

 

gson을 이용하여 리스트를 꺼내기

fun getConfig(sharedPref: SharedPreferenceProvider) : List<Config> {
    var res = sharedPref.get("key", "")
    val type = object : TypeToken<List<Config>>() {}.type
    if(res.isEmpty()) {
    res = emptyArray<List<Config>>().asList().toString()
    }
    return Gson().fromJson(res, type)
}

'안드로이드' 카테고리의 다른 글

webview scroll detecting  (0) 2019.09.06
Room에서 LiveData사용과 paging처리  (0) 2019.09.05
x86 emulation currently requires hardware acceleration  (0) 2019.02.22
library version check  (2) 2016.10.30
log 관리하기  (3) 2016.09.28

댓글