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, ""]
}
'Android' 카테고리의 다른 글
Kotlin DSL (1) - Kotlin DSL이란 무엇인가? (0) | 2022.12.13 |
---|---|
안드로이드 스튜디오 Arctic Fox 버전 이후 gradle allprojects 오류 해결 방법 (0) | 2022.02.05 |
Clean Architecture 1 - 클린 아키텍처란 무엇인가? (0) | 2022.01.17 |
안드로이드 4대 컴포넌트 (0) | 2021.12.27 |
BottomSheetDialogFragment에서 Dagger 사용하기 (0) | 2021.12.06 |