Shared Preferences in Android with Example - GeeksforGeeks

29 Oct, 2021
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. 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.
Shared Preferences
Saved Instance State
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.
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.
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.
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.  
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:
Java
// Storing data into SharedPreferencesSharedPreferences 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 edittextmyEdit.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 errormyEdit.commit();
Following is the sample byte code on how to read Data in Shared Preferences:
Java
// Retrieving the value using its keys the file name// must be same in both saving and retrieving the dataSharedPreferences 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 showString s1 = sh.getString("name", "");int a = sh.getInt("age", 0); // We can then use the dataname.setText(s1);age.setText(String.valueOf(a));
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:
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"    tools:ignore="HardcodedText">     <TextView        android:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_marginTop="32dp"        android:text="Shared Preferences Demo"        android:textColor="@android:color/black"        android:textSize="24sp" />     <!--EditText to take the data from the user        and save the data in SharedPreferences-->    <EditText        android:id="@+id/edit1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/textview"        android:layout_marginStart="16dp"        android:layout_marginTop="8dp"        android:layout_marginEnd="16dp"        android:hint="Enter your Name"        android:padding="10dp" />     <!--EditText to take the data from the user and         save the data in SharedPreferences-->    <EditText        android:id="@+id/edit2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/edit1"        android:layout_marginStart="16dp"        android:layout_marginTop="8dp"        android:layout_marginEnd="16dp"        android:hint="Enter your Age"        android:padding="10dp"        android:inputType="number" /> </RelativeLayout>
Output 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.
Java
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_PRIVATE);         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();         // write all the data entered by the user in SharedPreference and apply        myEdit.putString("name", name.getText().toString());        myEdit.putInt("age", Integer.parseInt(age.getText().toString()));        myEdit.apply();    }}
Reference: Shared Preferences | Android
adityamshidlyali
jemikp2000
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java