-
By 키워드를 이용한 Shared PreferenceAndroid & Kotlin 2022. 11. 18. 18:44
1. SharedPreferences 기본 사용법
val sharedPref = getSharedPreferences("name", Context.MODE_PRIVATE) with (sharedPref.edit()) { putString("key", "value") apply }
2. By 키워드를 통한 SharedPreferences 사용법
장점
- 값에 대한 접근, 수정이 매우 편함 (변수처럼 취급할 수 있음)
- 매번 getter, setter 를 구현해줄 필요가 없음
- SharedPreference 를 객체를 생성하거나 가져오지 않아도 됨
구현 방법
1. ReadWriteProperty 를 구현한 Preference class 를 정의한다
//PreferenceProperty.kt class StringPreference( private val preferences: Lazy<SharedPreferences>, private val name: String, private val defaultValue: String ) : ReadWriteProperty<Any, String?> { @WorkerThread override fun getValue(thisRef: Any, property: KProperty<*>): String { return preferences.value.getString(name, defaultValue) ?: defaultValue } override fun setValue(thisRef: Any, property: KProperty<*>, value: String?) { preferences.value.edit { putString(name, value) } } }
2. SharedPreference 객체를 생성한다.
//UserStorage.kt @Singleton class UserStorage @Inject constructor( @ApplicationContext val context: Context ) { private val prefs: Lazy<SharedPreferences> = lazy { context.applicationContext.getSharedPreferences( PREFS_NAME, Context.MODE_PRIVATE ) } ... }
3. by 키워드의 property delegate 를 통해 변수 정의
//UserStorage.kt @Singleton class UserStorage @Inject constructor( @ApplicationContext val context: Context ) { private val prefs: Lazy<SharedPreferences> = lazy { ... } var Session by StringPreference(prefs, SESSION, "") var isLogin by BooleanPreference(prefs, USER_LOGIN, false) companion object { const val SESSION = "session" const val USER_LOGIN = "user_login" } }
사용 예시
// get data val sessionCookie = userStorage.Session // set data userStorage.Session = cookie
By 키워드와 Delegate Pattern
위 구현 방식의 핵심은 by 키워드에 있고 by 키워드 는 위임 패턴을 코틀린 언어적으로 제공하고 있다.
이를 통해 정해진 방식으로만 내부 객체를 사용하도록 제한하고, 보호하는 효과를 얻을 수 있다.
해당 내용은 아래 "코틀린 by 키워드 알아보기" 에 자세히 명시 되어있다.
참고
코틀린 by 키워드 알아보기
What is the `by` keyword in Kotlin?
jisungbin.medium.com
[Android] by 키워드를 통해 SharedPreferences 사용하기 (1)
Android에서는 Key-Value 형태의 비교적 적은 데이터를 저장하기 위한 용도로 SharedPreferences API를 제공하고 있습니다.이를 통해 Room, Realm 혹은 파일 저장 등과 같은 방법을 쓰지 않아도 간단하게 디바
velog.io
'Android & Kotlin' 카테고리의 다른 글
Hilt 관련 리펙토링 기록 (@binds @Provides 차이 , UsecaseModule) (0) 2023.01.08 DialogFragment 오류 정리 (Radius , 크기 지정) (0) 2022.11.28 Android 13 알아보기 (Target SDK 33 으로 변경) (0) 2022.11.11 [ Android ] Context 와 메모리 릭 (0) 2022.07.27 [ Android ] CallAdapter, SealedClass 를 활용한 레트로핏 응답 처리 (0) 2022.07.12