theme: apple-basic
layout: intro
highlighter: shiki
lineNumbers: true
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)
Preferences DataStore
Proto Datastore
| Feature | SharedPreferences | PreferencesDataStore | ProtoDataStore |
|---|---|---|---|
| Async API | ✅ (only for reading changed values, via listener) | ✅ (via Flow and RxJava 2 & 3 Flowable) | ✅ (via Flow and RxJava 2 & 3 Flowable) |
| Synchronous API | ✅ (but not safe to call on UI thread) | ❌ | ❌ |
| Safe to call on UI thread | ❌1 | ✅ (work is moved to Dispatchers.IO under the hood) | ✅ (work is moved to Dispatchers.IO under the hood) |
| Can signal errors | ❌ | ✅ | ✅ |
| Safe from runtime exceptions | ❌2 | ✅ | ✅ |
| Has a transactional API with strong consistency guarantees | ❌ | ✅ | ✅ |
| Handles data migration | ❌ | ✅ | ✅ |
| Type safety | ❌ | ❌ | ✅ with Protocol Buffers |