The Wayback Machine - https://web.archive.org/web/20240926113815/https://www.geeksforgeeks.org/shared-preferences-in-android-with-examples/
Open In App

Shared Preferences in Android with Example

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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? 

Shared Preferences

Saved Instance State

Persist Data across user sessions, even if the app is killed and restarted, or the device is rebootedPreserves state data across activity instances in the same user session.
Data that should be remembered across sessions, such as the user’s preferred settings or 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 preferencesA 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  

  1. 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.
  2. 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 

  1. contains(String key): This method is used to check whether the preferences contain a preference. 
     
  2. 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. 
     
  3. getAll(): This method is used to retrieve all values from the preferences. 
     
  4. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. 
     
  5. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. 
     
  6. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences. 
     
  7. getLong(String key, long defValue): This method is used to retrieve a long value from the preferences. 
     
  8. getString(String key, String defValue): This method is used to retrieve a String value from the preferences. 
     
  9. getStringSet(String key, Set defValues): This method is used to retrieve a set of String values from the preferences. 
     
  10. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to register a callback to be invoked when a change happens to a preference. 
     
  11. 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:

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:inputType="number"
        android:padding="10dp" />
</RelativeLayout> 

Working with the MainActivity 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 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();
    }
}
Kotlin
import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var name: EditText
    private lateinit var age: EditText
    
    override fun onCreate(savedInstanceState: Bundle?) {
        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 fun onResume() {
        super.onResume()
        // Fetching the stored data from the SharedPreference
        val sh = getSharedPreferences("MySharedPref", MODE_PRIVATE)
        val s1 = sh.getString("name", "")
        val a = sh.getInt("age", 0)

        // Setting the fetched data in the EditTexts
        name.setText(s1)
        age.setText(a.toString())
    }

    // 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 fun onPause() {
        super.onPause()
        // Creating a shared pref object with a file name "MySharedPref" in private mode
        val sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE)
        val myEdit = sharedPreferences.edit()

        // write all the data entered by the user in SharedPreference and apply
        myEdit.putString("name", name.text.toString())
        myEdit.putInt("age", age.text.toString().toInt())
        myEdit.apply()
    }
}

Output:



Previous Article
Next Article

Similar Reads

How to View Data Stored in Shared Preferences in Android Studio?
Shared Preferences in Android is local storage where we can save our data using a key and value pair. It is generally used to store data in users' devices. Shared Preferences is also used for session management in Android apps where we are using login functionality. In this article, we will take a look at how we can view the data store in Shared Pr
4 min read
How to Delete Shared Preferences Data in Android?
In Android, Shared Preferences is a method of storing and fetching primitive data with the help of a key. This is file is stored inside the application in the form of an XML file. It is used to save data of types int, long, string, boolean, etc. In this article, we will show you how you could save and delete data from Shared Preferences in Android.
3 min read
Encrypted Shared Preferences in Android
Many times we want to save the data within the android application. This data is in the form of text and we generally prefer to store this data in the shared preferences. Shared preferences are not secure as we can simply view the data stored within the shared preferences and can easily access data within that file. To make the data stored in share
5 min read
Android Jetpack Compose Encrypted Shared Preferences
Many times we want to save the data within the android application. This data is in the form of text and we generally prefer to store this data in the shared preferences. Shared preferences are not secure as we can simply view the data stored within the shared preferences and can easily access data within that file. In this article, we will take a
7 min read
Android - Login and Logout Using Shared Preferences in Kotlin
Using Shared Preferences We can store data locally on our Android applications. In your Android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the user closes his app and reopens it then he should redirect to our Home screen, rather than opening a login screen. So in t
6 min read
Preferences DataStore in Android
Preference Data Store is used to store data permanently in android. Earlier we had to Shared Preferences for the same but since it is deprecated we are using Data Store now. A sample video 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 Kotlin language. [video m
4 min read
How to Implement Preferences Settings Screen in Android?
In many apps, we have seen the Settings screen which is most common in most of the apps. This settings screen is used to manage the preferences of the users. For creating this settings screen android provides a feature to make a settings preferences screen. In this article, we will take a look at implementing the preferences setting screen in Andro
7 min read
Android Jetpack Preferences
Nowadays we can observe that in almost all applications we use, a settings screen is available from where users can change their preferences according to them. For example apps like WhatsApp have options for dark mode and light mode, users can change the theme for an app with one click. Implementing a settings screen is a very good way we can provi
5 min read
Shared Element Transition in Android with Example
Shared Element Transition is one of the most seen animations in Android apps. This type of animation is used when we have to open an item from a ListView or RecyclerView. Shared Element Transition in Android determines how shared element views are animated from activity to activity or fragment to fragment. Now we will see the implementation of Shar
4 min read
Android Shared Element Transition with Kotlin
Shared element transition is seen in most of the applications which are used when the user navigates between two screens. This type of animation is seen when a user clicks on the items present in the list and navigates to a different screen. During these transitions, the animation which is displayed is called a shared element transition. In this ar
4 min read
Fragment to Fragment Communication in Android using Shared ViewModel
If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it
6 min read
Shared ViewModel in Android
In Android development, ViewModel serves as a means to facilitate data sharing among different fragments or activities. By utilizing the same ViewModel across multiple fragments, each fragment gains access to the shared data and functionality encapsulated within the ViewModel. This approach offers a streamlined method for enabling communication bet
5 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kot
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scroll
2 min read
NestedScrollView in Android with Example
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when
5 min read
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically he
6 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered can cause an activity to do the transition from o
6 min read
Floating Action Button (FAB) in Android with Example
The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app's UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this a
8 min read
Theming Floating Action Buttons in Android with Example
Prerequisite: Floating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with Example Android application developers want to seek the attention of the users by customizing and theming the android application widgets and keep more traffic of customers only by the design of the application. In this article, it has
12 min read
ArrayAdapter in Android with Example
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When y
3 min read
SlidingDrawer in Android with Example
SlidingDrawer is a common requirement in android mobiles to view the content whenever needed by sliding horizontally as well as vertically. In this article, let us check out Sliding Drawer which is used to hide the content out from the screen and allows the user to drag a handle to bring the content on the screen whenever needed in a very user-frie
9 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
ViewStub in Android with Example
In Android, ViewStub is a zero-sized invisible View and very flexible in that we can lazily inflate layout resources at runtime. It is a dumb and lightweight view and it has zero dimension. Depending upon the requirement, whenever in need we can inflate at runtime. This is a classic example to handle when there are complicated views to be handled.
6 min read
MVP (Model View Presenter) Architecture Pattern in Android with Example
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing
12 min read
Include and Merge Tags in Android with Example
Android apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the &lt;include/&gt; and &lt;merge/&gt; tags. Under &lt;merge/&gt; tags, we can specify a part of the layout that has to come in the main la
4 min read
Theming of Material Design EditText in Android with Example
Prerequisite: Material Design EditText in Android with Examples In the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, it'
4 min read
Theming Material Design Snackbars in Android with Example
In the previous article, it's been discussed Snackbar Material Design Components in Android. In this article, it's been discussed how we can theme material design Snackbar and increase the User Experience. Theming Example 1:This method is done using the styles.xml file. Where we need to override the default style of the Snackbar.Have a look at the
5 min read