Android Shared Preferences Tutorial


Sometimes you need some data to be available throughout our application so that you can read that data and use it in different scenarios like user sessions, app settings, etc. There are several ways to do that, one of the common way is to store data is global variables but problem is that data get lost when user closes the application. To eliminate this kind of problem Android provide us the very efficient class named Shared Preferences.

What is SharedPreferences?

SharedPreferences are key-value pairs of primitive data types (string, long, int, float and Boolean) that are saved in a file within your app file structure. You can access this file anywhere within the app to read or write data from file. You can’t access the file from another app so it’s pretty secure from that point of view.

Android stores shared preference files as XML file in shared_prefs folder in internal memory of device under DATA/data/[application package] directory. The DATA folder can be obtained by calling Environment.getDataDirectory() (usually it is /data).

Shared Preferences is application specific as the data is lost either you uninstall the application and clear the application data (From Settings).

Before starting tutorial lets us learn some basic information how to use shared preferences.

Initialization

Shared preferences in the application can be obtained by using getSharedPreferences() method. You also need to initialize the editor object to read and write in shared preferences. The code below is used to get application shared preferences

Here, getSharedPreferences(String name, int mode) method having two parameters one is the name of the file and other is the operational mode, returns the shared preferences object.

– PREFS_NAME is the name of the file.
– Context.MODE_PRIVATE is the operating mode.

SharedPreferences Modes

MODE_PRIVATE : This mode will make the shared preferences private to the application.
MODE_WORLD_READABLE : As the name suggests it is world readable, and it might be the reason for the security loopholes in your application. So you should use this mode with extra care.
MODE_WORLD_WRITEABLE : As the name suggests it is world writable, so it is even more dangerous than the world readable mode. So you should use this mode with extra care.
MODE_MULTI_PROCESS : It is deprecated from API 23, so we should not use it..
MODE_APPEND : If you don’t want to destroy your existing preferences you can use this mode to append the preferences with your existing one.

Storing data

Saving data into shared preferences is done by using editor object. You can save any primitive data types like boolean, float, int, long and string values in shared preferences by using method putDataType() like putString(), putInt(). The method takes two arguments first is the key and the second is the respective value. Key is always string and the second parameter is the data that we want to save. In order to save changes to shared preferences call editor.commit().

Reading data

Data can be read from saved preferences by calling getDataTye() method like getString() (For string). The method takes two arguments first is the key and the second is the respective default value. Key is always string and the second parameter is the default data that is returned if there is no value stored in correspondence to any key. Note this method should be called on Shared Preferences object not on Editor Object.

Deleting Data

Deleting data from shared preferences is very simple, you can delete particular value by calling remove(“key_name”) method of Editor. If you want to delete all the data, call clear() method of Editor.

Following will clear all the data from shared preferences





Let’s Get it Working

In this tutorial, we are going to learn the basic usage of SharedPreferences. To really understand the usage of shared preferences we will create an app. In this app, we are going to learn saving data in users profile creation screen and reading/deleting data on the user profile screen. This app shows actual usage of shared preferences operations. I assume that you had already created a new android project.

DownloadCode
 
github

Step 1) Update build.gradle file.

Before you can use Material Design in your projects you need to add the following compile line to your Gradle dependencies block in your build.gradle file and rebuilt the project.

Step 2) Update strings.xml.

Add the below string values to the strings.xml located in res ⇒ values ⇒ strings.xml.

Step 3) Update colors.xml.

Add the below color values to the colors.xml located in res ⇒ values ⇒ colors.xml.

Step 4) Create AppPreferences class.

Create a new class named AppPreferences, this class is used to perform shared preferences operations(store, read and clear) for all primitive data types (int, float, string, long and boolean).





Step 5) Create activity_create_profile.xml.

Now create a layout file for the CreateProfileActivity.java i.e activity_create_profile.xml and add the below code in your layout file. The code will create a simple form containing 3 input fields name, email and phone no, user type radio buttons and save data button to save data to shared preferences.

activity_create_profile.xml would result a screen like this:

Create Profile Screen

Step 6) Create CreateProfileActivity class.

Now create a class named CreateProfileActivity and add below code. Here I have written the code to fetch the data from input fields Name, Email, Phone no and storing it in shared preferences using the AppPreferences class discussed above. Also written code for navigation to profile screen after saving data.

The Screen below shows the filled form with valid values.

Create Profile Screen with data

Step 7) Create activity_profile.xml.

Now create a layout file for the ProfileActivity.java i.e activity_profile.xml and add the below code in your layout file. The code will create a simple view to show the data stored in shared preferences during profile creation.

activity_profile.xml would result a screen like this:

Profile Screen

Step 8) Create ProfileActivity class.

Now create a class named ProfileActivity and add below code. Here I have written code to show data to UI stored in shared preferences. Also written code to clear data from shared preferences and navigating back to CreateProfile Activity.

The Screen below shows the stored data in shared preference.

Profile Screen with data

Step 9) Update AndroidManifest.xml.

Last declare all the activities to manifest.

DownloadCode
 
github

Please feel free to comment as well as ask questions. And, yeah! If this post helps you please do share!

Enjoy Coding and Share Knowledge

Show Buttons
Hide Buttons