5. Android SharedPreferences Example | Android Settings Tutorial

SharedPreferences Can Save and Load Data

In this Android tutorial, we will learn about creating a settings menu using Android’s sharedPreferences. This sharedPreferences example will save the state of check boxes, strings, and other data that will be loaded each time the application starts. As long as the user doesn’t erase the data, nor uninstall the application, the data will be stored on the user’s phone. If you haven’t programmed with Android before, or if you think I’m moving a little fast in this tutorial, you should start with the Android basics series.

SharedPreferences Walk-through

Android SharedPreferences Project Setup

If you have done any sort of Android programming before, you have probably wanted to save some data, and that is probably why you have ended up here. SharedPreferences is the easiest way to save and load primitive data, whether you are looking to save the user’s name or whether you are creating a settings (or preferences) menu.

There are actually five different ways to save data for Android according the to Android Developers Page:

Network Connection: Store data on the web with your own network server.

We will learn about all of these in future tutorials, but as for now we are going to focus solely on shared preferences, and storing key-value pairs. What is a key-value pair? A key-value can be of any primitive data type, whether that be a string, boolean, int, double, or other primitive data type. For example:

String name = "Travis";

name would be “key” the and Travis would be the “value”.

So, now we know what a key-value pair is, we will be able to use sharedPreferences to save a bunch of stuff. Another example would be if we have our app save a boolean data type with key “music” with the value of “true” (or false). This could be a checkbox within a settings menu, and before we play any music within our app we would check sharedPreferences to see if “music” is set to “true” and if so, we would play music, if it was set to false, we wouldn’t play music. The user would then be able to go into the settings and change the state of the “music” key and that state would be saved forever (at least while the user doesn’t erase the data or uninstall the app), or until the user changes the state of the checkbox again.

So hopefully you now know a little be more about Android sharedpreferences. Look at the source code below to setup the structure of our sharedPreferences example that we will be using in the next couple of tutorials. In the next few Android tutorials we will continue to see how sharedPreferences can be used, so make sure you check that out.