android sharedpreferences

Android SharedPreferences Example – Android Storage Types Tutorial #1

Vamsi Tallapudi Android, Programming 0 Comments

Android SharedPreferences provides an easy and efficient way to store data in the form of Key value pairs in Android. Unlike other storage options whose setup is a bit complex, SharedPreferences provides an easy way to read and write data into a file.

What are SharedPreferences?

SharedPreferences are just key value pairs which are stored in an xml file. If we know the key, we can access the value.

android sharedpreferences

What kind of data can I store using Android SharedPreferences?

We can store all primitive data types like int, float, long, boolean, String in SharedPreferences. For data that is complex and bulkier than this, it is better to use sqlite, which we’ll also discuss in my future tutorials.

Accessing Android SharedPreferences

Accessing Android SharedPreferences can be done by using the following code:

We can observe that from the above lines of code, getSharedPreferences() method from context takes in two parameters:

  • Key
  • Mode

Key – It is the one which is used to save the datatype in SharedPreferences

Mode – Which sets whether the data should be visible to other apps. MODE_PRIVATE is the default mode.

Different Types of Modes Available:


File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it.


Database open flag: when set, the database is opened with write-ahead logging enabled by default.


File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).


Database open flag: when set, the database is opened without support for localized collators.

Writing data to Android SharedPreferences

To write data to Android sharedPreferences we need to create SharedPreferences.Editor by calling edit() method from SharedPreferences as follows:

Reading data from Android SharedPreferences


So where is my data stored?

The data for the respective app will be stored in the following directory:


Example Please:

Here is the video so that it would be easier to understand Android SharedPreferences with an example.


The sourcecode for the example created in the above Youtube Video on Android SharedPreferences is in the below link pointing to github.



This completes our tutorial on SharedPreferences. We’ll discuss about various other storage options available in Android in upcoming articles.


Related Posts