- Shared Preferences in Android with Example
- How are Shared Preferences different from Saved Instance State?
- How to Create Shared Preferences?
- Nested classes of Shared Preferences
- Following are the methods of Shared Preferences
- Following is a 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
- Save simple data with SharedPreferences
- Get a handle to shared preferences
- Kotlin
- Java
- Kotlin
- Java
- Write to shared preferences
- Kotlin
- Java
- Read from shared preferences
- Kotlin
- Java
Shared Preferences in Android with Example
One of the most Interesting Data Storage options 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. The 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. The code for that has been given in both Java and Kotlin Programming Language for Android.
Shared Preferences are suitable for 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 are Shared Preferences different from Saved Instance State?
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 register a callback to be invoked when a change happens to a preference.
- unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregister a previous callback.
Following is a sample byte code on how to write Data in Shared Preferences:
// Storing data into SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE); // Creating an Editor object to edit(write to the file) SharedPreferences.Editor myEdit = sharedPreferences.edit(); // Storing the key and its value as the data fetched from edittext myEdit.putString("name", name.getText().toString()); myEdit.putInt("age", Integer.parseInt(age.getText().toString())); // Once the changes have been made, we need to commit to apply those changes made, // otherwise, it will throw an error myEdit.commit();
Following is the sample byte code on how to read Data in Shared Preferences:
// Retrieving the value using its keys the file name must be same in both saving and retrieving the data SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_APPEND); // The value will be default as empty string because for the very // first time when the app is opened, there is nothing to show String s1 = sh.getString("name", ""); int a = sh.getInt("age", 0); // We can then use the data name.setText(s1); age.setText(String.valueOf(a));
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:
Save simple data with SharedPreferences
If you have a relatively small collection of key-values that you’d like to save, you can use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.
This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.
Caution: DataStore is a modern data storage solution that you should use instead of SharedPreferences . It builds on Kotlin coroutines and Flow, and overcomes many of the drawbacks of SharedPreferences .
Read the DataStore guide for more information.
Note: The SharedPreferences APIs are for reading and writing key-value pairs, and you shouldn’t confuse them with the Preference APIs, which help you build a user interface for your app settings (although they also use SharedPreferences to save the user’s settings). For information about the Preference APIs, see the Settings developer guide.
Get a handle to shared preferences
You can create a new shared preference file or access an existing one by calling one of these methods:
- getSharedPreferences() : Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
- getPreferences() : Use this from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don’t need to supply a name.
For example, the following code accesses the shared preferences file that’s identified by the resource string R.string.preference_file_key and opens it using the private mode so the file is accessible by only your app:
Kotlin
val sharedPref = activity?.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE)
Java
Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE);
When naming your shared preference files, you should use a name that’s uniquely identifiable to your app. A good way to do this is prefix the file name with your application ID. For example: «com.example.myapp.PREFERENCE_FILE_KEY»
Alternatively, if you need just one shared preference file for your activity, you can use the getPreferences() method:
Kotlin
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
Java
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Caution: The MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE modes have been deprecated since API level 17.
Starting with Android 7.0 (API level 24), Android throws a SecurityException if you use them. If your app needs to share private files with other apps, it may use a FileProvider with the FLAG_GRANT_READ_URI_PERMISSION . For more information, also see Sharing Files.
If you’re using the SharedPreferences API to save app settings, you should instead use getDefaultSharedPreferences() to get the default shared preference file for your entire app. For more information, see the Settings developer guide.
Write to shared preferences
To write to a shared preferences file, create a SharedPreferences.Editor by calling edit() on your SharedPreferences .
Note: You can edit shared preferences in a more secure way by calling the edit() method on an EncryptedSharedPreferences object instead of on a SharedPreferences object. To learn more, see the guide on how to work with data more securely.
Pass the keys and values you want to write with methods such as: putInt() and putString() . Then call apply() or commit() to save the changes. For example:
Kotlin
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return with (sharedPref.edit())
Java
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.saved_high_score_key), newHighScore); editor.apply();
apply() changes the in-memory SharedPreferences object immediately but writes the updates to disk asynchronously. Alternatively, you can use commit() to write the data to disk synchronously. But because commit() is synchronous, you should avoid calling it from your main thread because it could pause your UI rendering.
Read from shared preferences
To retrieve values from a shared preferences file, call methods such as getInt() and getString() , providing the key for the value you want, and optionally a default value to return if the key isn’t present. For example:
Kotlin
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return val defaultValue = resources.getInteger(R.integer.saved_high_score_default_key) val highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)
Java
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key); int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2023-04-12 UTC.