저장하려는 키-값 collection이 작은 경우 SharedPreferences를 이용한다.
새로운 공유 환경설정 파일을 생성하거나 기존 파일에 access 할 수 있다.
getSharedPreferences()
val sharedPref = activity?.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE)
getPreferences()
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt(getString(R.string.saved_high_score_key), newHighScore)
apply()
}
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
val defaultValue = resources.getInteger(R.integer.saved_high_score_default_key)
val highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)
implementation("androidx.datastore:datastore-preferences:1.0.0")
override suspend fun getSort(): Flow<String> {
return dataStore.data.catch { exception ->
if (exception is IOException) {
exception.printStackTrace()
emit(emptyPreferences())
} else {
throw exception
}
}.map {
it[SORT_MODE] ?: Sort.ACCURACY.by
}
}
override suspend fun saveSort(mode: String) {
dataStore.edit { setting ->
setting[SORT_MODE] = mode
}
https://developer.android.com/topic/libraries/architecture/datastore?hl=ko
https://www.inflearn.com/course/%EC%95%8C%EA%B8%B0%EC%89%AC%EC%9A%B4-modern-android/unit/112163