How to use SharedPreferences in Android to store, fetch and edit values
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
SharedPreferences in Android
SharedPreferences is a key-value pair storage mechanism in Android used for storing small amounts of primitive data as long as the user interacts with the application. It is typically used to store user settings, app preferences, login credentials, or any small set of key-value data needed across application sessions.
Getting Started with SharedPreferences
To utilize SharedPreferences, you need to create or get an existing instance of a SharedPreferences object. Here's how you can do it:
Here, "MyPreferences" is the name of the shared preferences file, and Context.MODE_PRIVATE is the operating mode that specifies the accessibility of this file. Using MODE_PRIVATE, the file can only be accessed by the application itself.
Storing Values
To store values in SharedPreferences, you need to use SharedPreferences.Editor. Here's a step-by-step process:
- Obtain the
SharedPreferencesinstance. - Get the
Editorfrom the above SharedPreferences instance. - Put value(s) using the editor.
- Apply or commit the changes.
apply()writes data to disk asynchronously and is recommended for non-blocking execution.commit()writes data synchronously and returnsboolean, indicating success or failure. It can block the execution.
Fetching Values
Fetching stored values is straightforward. You will use the get methods provided by the SharedPreferences class:
If the key doesn't exist, the method returns a default value provided by the user, such as "defaultName" for strings or 0 for integers.
Editing Values
You can modify the existing values using the same method for storing values. Simply call putX() for the key you want to update and apply the changes.
Removing Values
To remove specific entries, use remove() with the key name:
To clear all data, use the clear() method:
Modes
The Context.MODE constants control the access mode for shared preference files:
| Mode | Description |
MODE_PRIVATE | File is only accessible by the calling application. |
MODE_WORLD_READABLE | (Deprecated) Allows other applications to read but not write to the file. |
MODE_WORLD_WRITEABLE | (Deprecated) Allows other applications to read and write to the file. |
Best Practices
- Use
apply()instead ofcommit()when possible to avoid UI lag. - Keep data stored in SharedPreferences small to keep performance optimal.
- Use encryption for sensitive data before storing it.
Example Use Case
Below is a simple example demonstrating SharedPreferences usage in an Android Activity:
Conclusion
SharedPreferences is a simple and effective way to handle persistent data storage for key-value pairs. It is preferable for smaller pieces of data but should be used judiciously to avoid affecting application performance. For larger data sets, consider using a database solution like SQLite.
By following the provided methods and best practices, you will efficiently manage application state and user preferences in your Android application using SharedPreferences.
Related reading
- How to use Swift autoclosure
- How to use Swift documentation comments
- How to use Swift struct in Objective-C
- How to use the background thread in Objective-C?
- How to use ThreeTenABP in Android Project
- How to use UIScrollView in Storyboard
- How to use UIVisualEffectView to Blur Image?
- How to use WeakReference in Java and Android development?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.