서버에서 불러오지 않고 어플리케이션 로컬에 간단한 데이터를 저장하기 위한 목적으로 SharedPreferences를 사용한다. 간단한 데이터라고 하면 자동 로그인 여부나 온보딩 화면 보여준 여부 등 이라고 할 수 있다. 이 데이터는 앱을 삭제하기 전까지 유지된다.
Context의 getSharedPreferences() 으로 SharedPreference 파일을 불러올 수 있다.
private val preference = context.getSharedPreferences(KEY, Context.MODE_PRIVATE)
Key Enum Class
// 데이터를 저장할 때 Enum Class Key
enum class DataKey(val keyToString: String) {
LOGIN_ID("LOGIN_ID"),
IS_AUTO_LOGIN("IS_AUTO_LOGIN"),
}
데이터 저장
데이터를 저장하는 방법은 SharedPreferences에서 edit()을 호출하여 SharedPreferences.Editor를 만든다.
@SuppressLint("ApplySharedPref")
public inline fun SharedPreferences.edit(
commit: Boolean = false,
action: SharedPreferences.Editor.() -> Unit
) {
val editor = edit()
action(editor)
if (commit) {
editor.commit()
} else {
editor.apply()
}
}
edit은 apply 또는 commit 두 가지 방식으로 가능하다. apply()는 메모리 내 SharedPreferences 객체를 즉시 변경하지만 업데이트를 디스크에 비동기적으로 씁니다. 또는 commit()을 사용하여 데이터를 디스크에 동기적으로 쓸 수 있습니다. 그러나 commit()은 동기적이므로 기본 스레드에서 호출하는 것을 피해야 합니다. UI 렌더링이 일시중지될 수 있기 때문입니다.
SharedPreferences.Editor 안에서 putString() 또는 putBoolean() 과 같이 타입에 따라 put 함수를 사용하면 된다.
// String
fun putString(key: DataKey, value: String) {
preference.edit { putString(key.keyToString, value)}
}
// Boolean
fun putBoolean(key: DataKey, value: Boolean) {
preference.edit { putBoolean(key.keyToString, value)}
}
데이터 조회
SharedPreferences에서 getString() 또는 getBoolean() 과 같이 타입에 따라 get 함수를 사용하면 된다.
// String
fun getString(key: DataKey) : String {
return preference.getString(key.keyToString, null) ?: ""
}
// Boolean
fun getBoolean(key: DataKey) : Boolean {
return preference.getBoolean(key.keyToString, false)
}