Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

Android Essentials: Application Preferences

This post is part of a series called Android Essentials.
Android Essentials: Using the Contact Picker
Android Essentials: Application Logging

Android applications can store data in application preferences. In this tutorial, you learn how to store persistent application data with shared preferences.

The Android SDK provides helpful APIs for storing and retrieving application preferences. Preferences are stored as groups of key/value pairs and are available at the Activity level or shared across all of Activity classes for a given application (but not outside of the application package).

What Is A Preference?

Shared preferences are simply sets of data values that are stored persistently. By persistence, we are talking about data that persists across application lifecycle events. In other words, the application (or device, for that matter) can be started and stopped without losing the data. The next time the user launches the application, that data will still be available.

An individual preference is simply a key-value pair with a specific data type for the value. The preference key is simply a string that uniquely identifies the preference and the value is just that: the value of that preference.

For example, your application might want to store the user’s name. The application could have a single preference to store this information:

  • The data type of the preference could be a String
  • The key could be a string called “UserName”
  • The value would be the actual username string, such as “AndroidPowerUser123” or “Bob”

A preference can be any of a number of different data types. The following data types are supported by the SharedPreferences class:

  • Boolean values
  • Float values
  • Integer values
  • Long values
  • String values

How Shared Preferences Work

The Android SDK includes helpful classes for getting application preferences up and running easily. Preference functionality can be found in the SharedPreferences interface of the android.content package.

An application can have multiple sets of application preferences, where each set has a name. For example, a game application might have a set of preferences for user information (user name, email, high score, etc.) and a set of preferences for game state (current level, current score, etc.). Preferences can be stored at the activity or application level.

Application-level preferences are available across all activities. These preferences are retrieved using the application Context class method called getSharedPreferences() by name. For example:

import android.content.SharedPreferences;
…
SharedPreferences settings = 
    getSharedPreferences("MyGamePreferences", MODE_PRIVATE);

There is no limit to the number of sets of shared preferences your application can have. How your application organizes its preferences is up to you. However, you may want to declare your preference set names so that you can easily load and access the preferences from any Activity within your application. For example:

public static final String PREFERENCE_FILENAME = "AppGamePrefs";

An activity can also have private preferences. These preferences are only available within the specific Activity class and are not shared with other activities. An activity can only have one set of private preferences. The following code retrieves the activity’s private preferences:

import android.content.SharedPreferences;
…
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);

Setting Preferences

Saving preferences to your application is fairly straightforward. First, you must decide if you want application or activity preferences. Use the appropriate method to retrieve the appropriate SharedPreferences object: use the getPreferences() method of the Activity class for activity-level preferences or the getSharedPreferences() method of the Context class for application-level preferences.

Once you have a valid SharedPreferences object, you must use a SharedPreferences.Editor to add, modify, or delete preference content. To retrieve an Editor for a specific SharedPreferences object, use its edit() method. Make any changes to the preferences using the methods available in the Editor class. For example, the SharedPreferences.Editor class has helper methods for saving preferences of different data types:

  • Store boolean values with the putBoolean() method
  • Store float values with the putFloat() method
  • Store int values with the putInt() method
  • Store long values with the putLong() method
  • Store String values with the putString() method

Within the Editor, you can also remove a specific preference by name using the remove() method, or remove all preferences within the set using the clear() method. Once you’ve finished editing the SharedPreferences object, you can save your changes using the Editor’s commit() method.

For example, the following code retrieves a set of application preferences called “MyGamePreferences” and adds a string preference called “UserName” with a value of “Guest123” and a Boolean preference called “PaidUser” with a value of false.

import android.content.SharedPreferences;
…
SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
prefEditor.putString("UserName", "Guest123");
prefEditor.putBoolean("PaidUser", false);
prefEditor.commit();

Updating Preferences

Updating preferences is as simple as retrieving another SharedPreferences.Editor and making changes to a given preference by name. For example, the following code modifies the “PaidUser” preference:

SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
prefEditor.putBoolean("PaidUser", true);
prefEditor.commit();

Tip: As you can see, it can be useful to define each preference key as static final string variables so that a given preference is always stored in a regular, reproducible fashion. You don’t want random preference strings floating around in your code.

Retrieving Preferences

You don’t need an Editor to simply read preferences. Instead, retrieve the SharedPreferences object and use the appropriate method to retrieve a preference by name:

  • Retrieve boolean values with the getBoolean() method
  • Retrieve float values with the getFloat() method
  • Retrieve int values with the getInt() method
  • Retrieve long values with the getLong() method
  • Retrieve String values with the getString() method

Each of these methods has two parameters: the preference key string and a default value to return if the preference is undefined.

You can also check for the existence of a preference by name using the contains() method. You can also iterate through all preferences for a given set using the getAll() method of the SharedPreferences class.

Reacting to Preference Changes

Your application can listen for, and react to, changes to shared preferences by implementing a listener and registering it with the specific SharedPreferences object using the registerOnSharedPreferenceChangeListener() and unregisterOnSharedPreferenceChangeListener() methods.

Conclusion

Shared preferences (android.content.SharedPreferences) can be used to easily store application data. Application preferences are stored as key-value pairs, and can be many different data types, including numbers, strings and Boolean values. Different sets of preferences can be stored in named preference sets. Use shared preferences to store simple application data in a persistent manner.

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Advertisement