반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
관리 메뉴

코딩하기 좋은날

안드로이드 SharedPreferences 사용 예제(Kotlin) 본문

Android

안드로이드 SharedPreferences 사용 예제(Kotlin)

huiung 2020. 8. 3. 23:15
반응형

SharedPreferences 

 

SharedPreferences는 DB를 사용하지 않고 간단하게 로컬에 데이터를 저장 할 때 사용 할 수 있습니다.

 

이전에 포스팅한 롤 알리미를 만들 때도 이를 사용하여 유저들을 저장하여 사용하였습니다.

 

Key-Value 의 형태로 값을 저장하며 로컬에 파일형태로 저장되기 때문에 앱을 삭제하면 모든 데이터가 날아간다는 단점이 있습니다.

 

보통 Object로 선언을 한 뒤 자신이 set/get할 자료형에 대한 함수를 정의하는 방식으로 사용을 많이 하는 것 같습니다.

 

아래는 제가 사용한 예시입니다.

값을 쓰거나 수정하기 위해서는 getSharedPreferences를 통해서 객체를 얻어온 후 edit() 객체를 얻은 뒤 put... 을 통해 값을 쓸수 있습니다. 값을 변경한 후에는 apply(), 또는 commit()을 해주어야 합니다.

 

apply는 비동기적/ commit 은 동기적으로 처리되므로 commit 같은 경우 main Thread에서 이용을 하면 Thread를 block 시키기 때문에 문제를 일으 킬 수 있습니다. 대신 결과를 반환 받을 수 있습니다. (성공 여부) 따라서 이러한 작업이 필요 없다면 apply를 써주시면 되겠습니다.

 

SharedPreferences는 Thread-safe하다고 알려져 있으므로 비동기 작업에서도 문제 없이 사용 할 수 있을 것으로 보입니다.

 

값을 얻기 위해서는 객체를 얻어온 후 get...(key, default) 로 값을 받아 올 수 있습니다. default에 들어갈 내용은 인자로 전달된 key값에 해당하는 값이 없을 경우 return 하게 되는 값입니다. 

 

object Preferences {

    private lateinit var preferences: SharedPreferences

    fun setAPI(context: Context, key: String, value: String) {
        preferences = context.getSharedPreferences("API", Activity.MODE_PRIVATE)
        val editor = preferences.edit()
        editor.putString(key, value)
        editor.apply()
    }

    fun getAPI(context: Context, key: String) : String? {
        preferences = context.getSharedPreferences("API", Activity.MODE_PRIVATE)
        return preferences.getString(key, " ")
    }

    fun setBool(context: Context, key: String, value: Boolean) {
        preferences = context.getSharedPreferences("API", Activity.MODE_PRIVATE)
        val editor = preferences.edit()
        editor.putBoolean(key, value)
        editor.apply()
    }

    fun getBool(context: Context, key: String) : Boolean {
        preferences = context.getSharedPreferences("API", Activity.MODE_PRIVATE)
        return preferences.getBoolean(key, false)
    }

    fun setString(context: Context, key: String, value: String) {
        preferences = context.getSharedPreferences("SummonerID", Activity.MODE_PRIVATE)
        val editor = preferences.edit()
        editor.putString(key, value)
        editor.apply()
    }

    fun getString(context: Context, key: String) : String? {
        preferences = context.getSharedPreferences("SummonerID", Activity.MODE_PRIVATE)
        return preferences.getString(key, "NoID")
    }

    fun getAll(context: Context) : MutableMap<String, *>? {
        preferences = context.getSharedPreferences("SummonerID", Activity.MODE_PRIVATE)
        val arr = preferences.all
        return arr
    }

    fun removeString(context: Context, key: String) {
        preferences = context.getSharedPreferences("SummonerID", Activity.MODE_PRIVATE)
        val editor = preferences.edit()
        editor.remove(key)
        editor.apply()
    }

    fun setLong(context: Context, key: String, value: Long) {
        preferences = context.getSharedPreferences("matchInfo", Activity.MODE_PRIVATE)
        val editor = preferences.edit()
        editor.putLong(key, value)
        editor.apply()
    }

    fun getLong(context: Context, key: String) : Long {
        preferences = context.getSharedPreferences("matchInfo", Activity.MODE_PRIVATE)
        return preferences.getLong(key, -1) //default 값
    }

}

 

실제로 사용 할 경우 아래와 같이 context를 전달 한 후 key or key,value를 전달해 주면 됩니다.

 

Preferences.getString(this, str)
Preferences.setString(this, key, value)

 

Context에 대해

 

ApplicationContext vs ActivityContext

 

위의 코드를 보면 context에 this를 준것을 알 수 있습니다. (Activity 에서 사용한 코드입니다.)

두가지 Context중 어떤 것을 사용해야 할 지 고민을 하였는데 아래 링크에서 많은 도움을 받았습니다.

정말 필요한 경우가 아니면  ApplicationContext의 사용은 지양해야 한다고 합니다. (메모리 leak을 쉽게 일으킴)

 

그리고 이러한 정말 필요한 경우는 액티비티에서 어떤 서비스에 bind 한다던지 Activity/ Service의 life cycle을 넘어선 어떤 global 한 context가 필요한 경우(?) 정도가 될 것 같습니다. 또한 ApplicationContext가 왜 필요한지 모른다면 대부분 그것을 사용할 필요가 없다 라는 말도 있습니다. 따라서 꼭 필요한 경우가 아니라면 basecontext를 사용하면 될 것 같습니다.

 

https://stackoverflow.com/questions/9109073/application-context-for-sharedpreferences

반응형