Shared Preferences in Android with Example
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 a simple shared preference 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. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Shared Preferences are 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, it’s preferred to save 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?
Saved Instance State
|Persist Data across user sessions, even if the app is killed and restarted, or the device is rebooted||Preserves state data across activity instances in the 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 the currently selected tab or current state of activity.|
|A common use is to store user preferences||A common use is to recreate the state after the device has been rotated|
How to Create 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 with the app. When you want to get the values, call the getSharedPreferences() method. Shared Preferences provide modes of storing the data (private mode and public mode). It is for backward compatibility- use only MODE_PRIVATE to be secure.
public abstract SharedPreferences getSharedPreferences (String name, int mode)
This method takes two arguments, the first being the name of the SharedPreference(SP) file and the 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 on the device
MODE_PRIVATE keeps the files private and secures the user’s data.
MODE_APPEND is used while reading the data from the SP file.
Nested classes of Shared Preferences
- SharedPreferences.Editor: Interface used to write(edit) data in the 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.
Following are the methods of Shared Preferences
- contains(String key): This method is used to check whether the preferences contain 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.
Following is sample byte code on how to write Data in Shared Preferences:
Following is the sample byte code on how to read Data in Shared Preferences:
Example to Demonstrate the use of Shared Preferences in Android
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, the user will not have to fill in details again and again. Invoke the following code inside the activity_main.xml file to implement the UI:
Working with the MainActivity.java file to handle the two of the EditText to save the data entered by the user inside the SharedPreferences. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Reference: Shared Preferences | Android