Free Android app covering all aspects of addiction, including prevention and treatment

Using Android's SharedPreferences to save persistent data: a practical example and tutorial

  • Written by  Clive

Use SharedPreferences for persistant data

User Preference Settings

SharedPreferences are not the same as the typical user preferences where one, for example selects the preferred default sound, text size, colours, etc. for an app.

 

Android SharedPreferences settings

What are SharedPreferences?

SharedPreferences are key-value pairs of primitive data types that are saved in a file within an apps file structure. You can then access this file from anywhere within the app to either put data into the file or take data out of the file. You can’t access the file from another app so it’s pretty secure from that point of view.

Where would you use SharedPreferences?

You would for example use SharedPreferences in a game where you would save the user’s name, high score, and state of the game when they logged off. Then the next time they log in, their score and game level would be retrieved from the preference file and they would continue the game from where they ended it when they logged off.

Save your data in a single or multiple SharedPreferences files

You can save your preferences data in a single file or in multiple files, depending on your needs. The process is the same except for the SharedPreferences object that you get.

In the case of a single file, call getPreferences() to get a SharedPreferences object and for multiple files, call getSharedPreferences() and pass it a name for the file as a parameter.

  • getPreferences() - for Activity level preferences. Each Activity will have it's own preference file
  • getSharedPreferences() - for application-level preferences. You can access the preference file from anywhere in the application
Retrieving the data

Once you have the SharedPreferences object, you can use a number of get<type> methods to retrieve the values.

Saving your data

Saving the data is pretty straight forward too. Simply use the SharedPreferences.Editor class to get an Editor object by calling edit() on the relevant SharedPreferences object. Then use the put<type> methods to save the data, finalising the process by calling apply() or commit() on the Editor object.

The difference between apply() and commit()

apply()

This saves your data into memory immediately and saves the data to disk on a separate thread. So there is no chance of blocking the main thread (your app won’t hang).

It is the preferred technique but has only been available since Gingerbread (API 9, Android 2.3).

commit()

Calling this will save the data to the file however, the process is carried out in the thread that called it, stopping everything else until the save is complete. It returns true on successful completion, false on failure.

Use commit() if you need confirmation of the success of saving your data or if you are developing for pre-Gingerbread devices. commit() has been available since API 1

Type of data that you can save

Use SharedPreferences to save and retrieve primitive data types in key-value pairs (boolean, float, int, long, strings). As of Honeycomb (API 11, Android 3.0) you can also save Set<String> sets of String values.

Here's a Tutorial for using SharedPreferences to save persistant data

Using a single SharedPreferences file

The first thing you need to do is create SharedPreferences and Editor objects:

SharedPreferences object

Also, create a constant for the operating mode. This is the file creation mode, which determines whether to create a private of public file when saving the SharedPreferences file. The default is MODE_PRIVATE which only allows access to the file by the app that created it.

Android SharedPreferences file creation mode

The data we want to save in our SharedPreferences file

Here’s the data that we want to save:

Android SharedPreferences primitive data types

Use the SharedPreferences.Editor to put the data into the file

Now get instances of the SharedPreferences and Editor objects. Notice that there is no need to pass a file name as a parameter when creating the preferenceSettings object, we only pass the file creation mode constant:

Android SharedPreferences getPreferences()

We can now add our data to the file (note that it does not save the data at this stage). Use the Editor’s put<type> methods to insert the data. This is the general format:

preferenceEditor.put<type>(key, value)

And here’s what it looks like using our example data:

Android SharedPreferences put methos

Calling commit() on the editor saves the file. You could use the return value of the commit to confirm whether or not the file was successfully saved.

Getting the data out of the SharedPreferences file

Make sure that you have an instance of the SharedPreferences object:

Android SharedPreferences getPreferences() private mode

Use the SharedPreferences get<type> methods to get the data out of the file:

 Android SharedPreferences get<type> methods

Simply pass the relevant key and default value for the data that you want. The default value is used in case there is no matching value to the supplied key.

Using SharedPreferences to save data in a unique file

If you want to save the data in a file of your choice, the procedure is exactly the same as above except that you need to pass a file name when instantiating the SharedPreferences object.

Create the objects

As above, create the file creation mode constant and also create a constant for your file name:

Android SharedPreferences Editor

Create the SharedPreferences and Editor objects:

SharedPreferences unique file name

Instantiate the SharedPreferences and Editor objects

Instantiate a SharedPreferences object, passing your file name and file creation mode constants as parameters. Then instantiate an Editor for this SharedPreferences object:

Android SharedPreferences getSharedPreferences()

Now you are ready to put your data into the file using the SharedPreferences put<type> methods. Here’s what it looks like:

SharedPreferences put<type> methods

commit() returns true or false, depending on the success of saving the file. Here we assign this value to the boolean variable successfullySaved which you can use elsewhere if a further action depended on whether or not the file was successfully saved.

Getting the data out of your unique file

Make sure that you have an instance of the SharedPreferences object:

SharedPreferences object

Then use the SharedPreferences get<type> methods to retrieve the data:

SharedPreferences get<type> methods

Simply pass the relevant key and default value for the data that you want. The default value is used in case there is no matching value to the supplied key.

Saving sets of String values

As of Honeycomb (API 11, Android 3.0) you can also save Set<String> sets of String values.

Here's an Example for saving Sets of Strings in SharedPreferences files

Refer to the above examples for getting the SharedPreferences and Editor objects for the relevant use case (either using the single default file or your own unique file).

Let’s say we have the following Set:

Android SharedPreferences Set<String>

We would use the putStringSet(key, value) method to put the data in the file and call commit() to finalise the save:

SharedPreferences saving String Sets

Getting a String Set out of the file

Use the SharedPreferences get<type> method to retrieve the set from the file:

Retrieving String Sets from SharedPreferences

SharedPreferences are a quick, easy, and very versatile, way of saving primitive data that can be accessed across the app.

Be sure to read the official documentation for further details.

You may also be interested in our Firebase tutorial, Using a Firebase Realtime Database in your app

Also check out our Realm tutorial, Realm databases for Android beginners

Using Android Studio for development

Although still under development, the latest edition of Android Studio is stable. It’s a great IDE for developing Android apps, making the process quick and easy.

Check out the eBook, Android Studio: How to guide and tutorial which will show you how to install and use Android Studio to develop Android apps quickly and efficiently.