Describe how to use Shared Preferences for data storage in Android.
Instruction: Explain the concept of Shared Preferences and provide an example of when to use it for storing data.
Updated
Official answer
SharedPreferences stores small named key/value settings, such as a chosen theme or whether the user wants an optional feature. Obtain a named instance with Context.getSharedPreferences and MODE_PRIVATE, then use an Editor to put/remove values. Reads supply a documented default for a missing key; keep each key's type consistent.
For example, save a boolean called reminders_enabled after the user's choice and read it with getBoolean("reminders_enabled", false). This records app preference only. It does not grant Android's notification permission, enable a blocked notification channel or override other system/user restrictions.
apply updates the in-memory value immediately and schedules the disk write asynchronously; it provides no disk-success result. commit writes synchronously and returns success/failure, so avoid blocking the main thread with it. An async API name does not mean all lifecycle-related I/O costs disappear. Do not use ordinary read-modify-write sequences as an atomic shared counter.
MODE_PRIVATE provides the normal app sandbox boundary, not encryption or a promise against every backup/device threat. Do not store secrets just because a preferences file is private. For new work, Android recommends DataStore, which supplies coroutine/Flow-based updates; plan migration and defaults explicitly. Use a database for relational or larger datasets.
Test missing keys, changed types, migration and restart behavior. Separate the saved user preference from the actual ability to execute the feature.