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
// 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(); |
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 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.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" tools:context=".MainActivity"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:layout_marginLeft="50dp" android:text="Shared Preferences Demo" android:textSize="24dp" /> <EditText android:layout_width="match_parent" android:layout_below="@+id/textview" android:hint="Enter your Name" android:padding="10dp" android:id="@+id/edit1" android:layout_height="wrap_content"/> <EditText android:layout_width="match_parent" android:layout_below="@+id/edit1" android:hint="Enter your Age" android:padding="10dp" android:id="@+id/edit2" android:layout_height="wrap_content"/> </RelativeLayout> |
MainActivity.java
// Android app to show the working of SharedPreference package com.example.sharedpreferencedemo; import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText name, age; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.edit1); age = findViewById(R.id.edit2); } // Fetch the stored data in onResume() // Because this is what will be called // when the app opens again @Override protected void onResume() { super.onResume(); // Fetching the stored data // from the SharedPreference SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_APPEND); String s1 = sh.getString("name", ""); int a = sh.getInt("age", 0); // Setting the fetched data // in the EditTexts name.setText(s1); age.setText(String.valueOf(a)); } // Store the data in the SharedPreference // in the onPause() method // When the user closes the application // onPause() will be called // and data will be stored @Override protected void onPause() { super.onPause(); // Creating a shared pref object // with a file name "MySharedPref" in private mode SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE); SharedPreferences.Editor myEdit = sharedPreferences.edit(); myEdit.putString("name", name.getText().toString()); myEdit.putInt("age", Integer.parseInt( age.getText().toString())); myEdit.commit(); } } |
Working Demo for the above app: https://drive.google.com/open?id=1wVMlkDzHjxBwadJb0QGAaiXjW69ZRS4W
Reference: Shared Preferences | Android
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Android | AdMob Banner Ads for Android Studio
- Android | Android Application File Structure
- Android | AdMob Interstitial Ads for Android Studio
- Android | How to Create/Start a New Project in Android Studio?
- Android | Running your first Android app
- Android | How to add Radio Buttons in an Android Application?
- Android | How to Request permissions in Android Application?
- Difference between Android 1.1 and Android 4.0.1
- Difference between Android 1.1 and Android 2.3.4
- Difference between Android 1.0 and Android 1.1
- Difference between Android 1.0 and Android 7.1
- Difference between Android 1.0 and Android 2.3
- Difference between Android 1.0 and Android 2.2
- Difference between Android 1.0 and Android 1.6
- Difference between Android 1.0 and Android 2.1
- Difference between Android 1.0 and Android 2.0.1
- Difference between Android 1.0 and Android 2.0
- Difference between Android 1.0 and Android 1.5
- Difference between Android 1.0 and Android 2.3.3
- Difference between Android 1.0 and Android 4.2.1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.

