One of the most Interesting Data Storage option Android provides its users is Shared Preferences. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage. Shared Preferences can be thought of as a dictionary or a key/value pair. For example, you might have a key being “username” and for the value, you might store the user’s username. And then you could retrieve that by its key (here username). You can have simple shared preferences API that you can use to store preferences and pull them back as and when needed. Shared Preferences class provides APIs for reading, writing and managing this data.
Shared Preferences is suitable in different situations. For example, when the user’s settings need to be saved or to store data that can be used in different activities within the app. As you know, onPause() will always be called before your activity is placed in the background or destroyed, So for the data to be saved persistently we prefer saving it in onPause(), which could be restored in onCreate() of the activity. The data stored using shared preferences are kept private within the scope of the application. However, shared preferences are different from that activity’s instance state.
How is Shared Preferences different from Saved Instance State?
|Shared Preferences||Saved Instance State|
|Persist Data across user sessions, even if app is killed and restarted, or device is rebooted||Preserves state data across activity instances in same user session.|
|Data that should be remembered across sessions, such as user’s preferred settings or their game score.||Data that should not be remembered across sessions, such as currently selected tab or current state of activity.|
|Common use is to store user preferences||Common use is to recreate state after the device has been rotated|
How to Create our Shared Preferences?
The first thing we need to do is to create one shared preferences file per app. So name it with the package name of your app- unique and easy to associate the app. When you want to get the values, call getSharedPreferences() method. Shared Preferences provide modes of storing the data (private mode and public mode). It is for the backward compatibility- use only MODE_PRIVATE to be secure.
public abstract SharedPreferences getSharedPreferences (String name, int mode)
This method takes two arguments, first being the name of the SharedPreference(SP) file and other is the context mode that we want to store our file in.
- MODE_PUBLIC will make the file public which could be accessible by other applications in the device
- MODE_PRIVATE keeps the files private and secure user’s data.
- MODE_APPEND is used while reading the data from SP file.
Nested classes of Shared Preferences
- SharedPreferences.Editor: Interface used to write(edit) data in SP file. Once editing has been done, one must commit() or apply() the changes made to the file.
- SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread.
Methods of Shared Preferences
- contains(String key): This method is used to check whether the preferences contains a preference.
- edit(): This method is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
- getAll(): This method is used to retrieve all values from the preferences.
- getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences.
- getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences.
- getInt(String key, int defValue): This method is used to retrieve an int value from the preferences.
- getLong(String key, long defValue): This method is used to retrieve a long value from the preferences.
- getString(String key, String defValue): This method is used to retrieve a String value from the preferences.
- getStringSet(String key, Set
defValues): This method is used to retrieve a set of String values from the preferences.
- registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to registers a callback to be invoked when a change happens to a preference.
- unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback.
How to Write Data in Shared Preferences
How to Read Data in Shared Preferences
Example to demonstrate use of Shared Preferences:
Below is the small demo for Shared Preferences. In this particular demo, there are two EditTexts, which save and retain the data entered earlier in them. This type of feature can be seen in applications with forms. Using Shared Preferences, user will not have to fill in details again and again.
Working Demo for the above app: https://drive.google.com/open?id=1wVMlkDzHjxBwadJb0QGAaiXjW69ZRS4W
Reference: Shared Preferences | Android
- Android | What is Toast and How to use it with Examples
- Android | Horizontal RecyclerView with Examples
- Screen Orientations in Android with Examples
- EditText widget in Android using Java with Examples
- Different ways to hide Action bar in Android with Examples
- Difference between Java and Kotlin in Android with Examples
- TextView widget in Android using Java with Examples
- Android | Implicit and Explicit Intents with Examples
- Firebase RealTime Database with Operations in Android with Examples
- Android | How to Create/Start a New Project in Android Studio?
- Android | AdMob Interstitial Ads for Android Studio
- Android | AdMob Banner Ads for Android Studio
- Android | How to Request permissions in Android Application?
- Android | How to add Radio Buttons in an Android Application?
- Android | Android Application File Structure
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.