앙큼한 개발기록

[android] kotlin에서 SharedPreference 사용하기 본문

개발/android

[android] kotlin에서 SharedPreference 사용하기

angkeum 2023. 5. 17. 21:57

안드로이드에서 자동 로그인, 간단한 정보를 저장할때 

사용되는 sharedpreperence를 이번에 

object로 정리해 보았다. 

 

 

SharedPreferenceAccount.kt

object SharedPreferenceAccount {

    const val ACCOUNT: String = "account"
    const val TOKEN: String = "account_token"
    const val IS_LOGIN: String = "account_is_login"

    fun setString(context: Context, key: String, value: String) {
        val prefs : SharedPreferences = context.getSharedPreferences(ACCOUNT, Context.MODE_PRIVATE)
        val editor : SharedPreferences.Editor = prefs.edit()
        editor.putString(key, value)
        editor.apply()
    }
    fun setBoolean(context: Context, key: String, value: Boolean) {
        val prefs : SharedPreferences = context.getSharedPreferences(ACCOUNT, Context.MODE_PRIVATE)
        val editor : SharedPreferences.Editor = prefs.edit()
        editor.putBoolean(key, value)
        editor.apply()
    }
    fun setDateToString(context: Context, key: String, date: Date) {
        val prefs: SharedPreferences = context.getSharedPreferences(ACCOUNT, Context.MODE_PRIVATE)
        val editor: SharedPreferences.Editor = prefs.edit()
        val dateString = Common.dateTimeFormat(date)
        editor.putString(key, dateString)
        editor.apply()
    }

    fun getString(context: Context, key: String): String {
        val prefs : SharedPreferences = context.getSharedPreferences(ACCOUNT, Context.MODE_PRIVATE)
        return prefs.getString(key, "").toString()
    }
    fun getBoolean(context: Context, key: String): Boolean {
        val prefs: SharedPreferences = context.getSharedPreferences(ACCOUNT, Context.MODE_PRIVATE)
        return prefs.getBoolean(key, false)

    }

    fun clear(context: Context) {
        val prefs : SharedPreferences = context.getSharedPreferences(ACCOUNT, Context.MODE_PRIVATE)
        val editor : SharedPreferences.Editor = prefs.edit()
        editor.clear()
        editor.apply()

        val token = this.getString(context, TOKEN)
        if (token.isNotBlank()) {
            this.setString(context, TOKEN, token)
        }

        this.setBoolean(context, IS_LOGIN, false)
    }

}

 

token 값과 is_login은 별도로 구분해서 저장하였는데 

인터넷이 끊겼을 때 로그아웃 하고나서 다시 로그인인을 시도 하거나 

이전에 로그인한지 안한지를 체크 하기 위한 값으로 활용 하였다. 

 

끝.

Comments