Shared Preferences
Storing data in Android apps is essential for various reasons, such as maintaining user preferences, saving app settings, caching data for offline use, and storing user-generated content. One common method for storing small amounts of user-specific data is through SharedPreferences. Some of its key features include:
- The Shared Preferences APIs provide a convenient way to save and retrieve primitive key-value pairs, typically for small application data such as settings or user authentication.
- The stored data persists and can be deleted either upon application uninstallation or by explicitly deleting SharedPreferences data using specific methods provided by the APIs.
- The data stored can include various types such as booleans, floats, integers, longs, and strings. Java objects can also be stored by converting them into JSON strings using libraries like GSON.
- The stored data can be accessed by viewing the application folder on the device or using the File Explorer on an emulator. The data is stored as an XML file located at: /data/data/APP_PACKAGE/shared_prefs/.
-
To ensure persistent data storage, it is commonly (but not always!) saved in the
onPause()
method, which is called when an activity is no longer in the foreground. Restore the data where needed in theonCreate()
method of the activity.
Storing Values
-
Create an instance of the SharedPreferences class by calling the
getSharedPreferences()
method, passing a name for the SharedPreferences file and a mode. The name is a unique identifier for the file, and the mode determines its accessibility and visibility. -
Obtain an instance of the SharedPreferences.Editor class by calling the
edit()
method on the SharedPreferences object. The Editor class provides methods to modify the data. -
Use methods like
putString()
,putInt()
,putBoolean()
, etc., to store values of different types. -
Use
apply()
to save changes asynchronously orcommit()
to save them synchronously, which returns a boolean indicating success.
Retrieving Stored Values
- Use appropriate getter methods based on the type of value you want to retrieve.
-
For example, use
getString()
for strings,getInt()
for integers,getLong()
for longs, andgetAll()
to retrieve all values.
When to Use SharedPreferences
SharedPreferences are suitable for small amounts of data, such as preferences and settings. For more complex or larger datasets, consider other storage mechanisms like databases or file storage. The choice of storage depends on the type of data, app requirements, and trade-offs between simplicity, performance, and data management.
Data Security
Data security is an important consideration for any data stored using SharedPreferences. Proper encryption should be implemented to make the XML file unreadable to unauthorized users.
-
Example code for encrypting data stored in SharedPreferences:
SharedPreferences Data Security
Note:
With the arrival of Jetpack, there is a new alternative to SharedPreferences in the form of Preferences DataStore. DataStore addresses some drawbacks
of SharedPreferences, such as synchronous APIs, lack of error signaling (e.g., IOException
), and lack of transactional APIs. It uses Kotlin Flow,
making it compatible with LiveData, coroutines, and modern Android development techniques. While SharedPreferences remain reliable and easy to use, the DataStore
API is advantageous in certain use cases, especially when working with Jetpack components.
Shared Preferences Example
// Get an instance of SharedPreferences SharedPreferences preferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); // Write a value to SharedPreferences SharedPreferences.Editor editor = preferences.edit(); editor.putString("key", "value"); editor.apply(); // Read a value from SharedPreferences (for string here) String value = preferences.getString("key", "default_value");
The default value in SharedPreferences acts as a fallback that is returned when the requested key doesn't have an associated value in the SharedPreferences
file. This prevents unexpected null
values. If the key "key" exists in the file, the corresponding value is returned; otherwise,
the specified default value (e.g., "default_value"
) is returned.
Context.MODE_PRIVATE
makes the data accessible only within the application, providing security and privacy. For sharing data between
applications, use ContentProvider or FileProvider.