Android

SharedPreference를 효율적으로 사용해보기

c0de_h0ng 2022. 1. 17. 18:27
728x90

애플리케이션을 개발할 때 10개 중 9개는 무조건 들어가는 기능 중에 로그인이 있다. 로그인 기능 중에서 단골 옵션인 자동 로그인 같은 경우에는 SharedPreference를 사용한다. 그 외에도 SharedPreference를 자주 사용하게 되는 데 필요한 클래스마다 SharedPreference를 사용하게 되면 코드가 깔끔하지 못하다. SharedPreference를 한 곳에서 관리할 수 있는 방법을 찾던 중에 출처 블로그를 통해서 참고해 보았다.

먼저 build.gradle/app에 아래와 같이 의존성을 추가해야 한다.

implementation 'androidx.preference:preference-ktx:1.1.1'
object PreferenceHelper {

    fun getSharedPrefs(context: Context, name: String): SharedPreferences {
        return context.getSharedPreferences(name, Context.MODE_PRIVATE)
    }

    private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
        val editor = this.edit()
        operation(editor)
        editor.apply()
    }

    operator fun SharedPreferences.set(key: String, value: Any?) {
        when (value) {
            is String? -> edit { it.putString(key, value) }
            is Int -> edit { it.putInt(key, value) }
            is Boolean -> edit{ it.putBoolean(key, value) }
            is Float -> edit { it.putFloat(key, value) }
            is Long -> edit { it.putLong(key, value) }
            else -> throw UnsupportedOperationException("Error")
        }
    }

    @Suppress("UNCHECKED_CAST")
    operator fun <T> SharedPreferences.get(key: String, defaultValue: T? = null): T {
        return when (defaultValue) {
            is String, null -> getString(key, defaultValue as? String) as T
            is Int -> getInt(key, defaultValue as? Int ?: -1) as T
            is Boolean -> getBoolean(key, defaultValue as? Boolean ?: false) as T
            is Float -> getFloat(key, defaultValue as? Float ?: -1f) as T
            is Long -> getLong(key, defaultValue as? Long ?: -1) as T
            else -> throw UnsupportedOperationException("Error")
        }
    }

}

SharedPreference를 관리할 때 정보를 저장하는 set과 정보를 가져오는 get을 operation으로 만들어 주었다. 호출 시 타입에 따라서 저장하고 가져올 수 있다.

class LoginPreference @Inject constructor(
    private val context: Context
) {

    private val prefs = PreferenceHelper.getSharedPrefs(context, LOGIN_DATA)

    fun setLoginData(id: String, password: String) {
        prefs[ID] = id
        prefs[PWD] = password
    }

    fun getIdData(): String = prefs[ID, ""]

    fun getPasswordData(): String = prefs[PWD, ""]

}