Advertisement
Android SDK

Android Essentials: Application Preferences

by

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

Related Posts
  • Code
    Web Development
    Laravel Unwrapped: Session, Auth and CacheLaravel wide retina preview
    Join me as we learn how to use Laravel's component-based system, Illuminate. Additionally, we'll see how to utilize service providers, Laravel's manager system, the Session, Auth, and Cache components, and the Store, Guard, and Repository libraries.Read More…
  • Code
    Creative Coding
    Using WordPress For Web Application Development: Available Features, Part 7: CachingApplication foundation 400
    When it comes to building web applications, one of the most important things that we have to constantly be mindful of is performance. As they say, performance is a feature. And regardless of if you're a designer, developer, or a user, you know this intuitively to be true: When it comes to applications, we hate waiting. We get frustrated when things don't perform fast enough, or we have to wait longer than we believe that we should.Read More…
  • Code
    Android SDK
    Android SDK: Detecting GesturesAndroid preview@2x
    The Android SDK supports a variety of gestures you can detect, allowing you to tailor the ways in which users interact with your applications. In this tutorial, we will look at the framework that allows developers to add gesture detection to a simple application, working through the process of supporting the fling gesture and outlining how to support other gestures. Once you've completed the development for a basic fling function, you'll be able to add additional gestures to the application yourself.Read More…
  • Code
    Android SDK
    Android SDK: Next StepsAndroid preview@2x
    In this series, we've begun learning how to develop Android applications from scratch. We started exploring the development tools, got acquainted with the basic elements in an application project, looked at user interface design, interactivity, resources, and data, and we've also took a closer look at what happens when your application is running. What we've covered so far should put you in a good position to get started creating functional Android applications, but Android has a lot more to offer so the range of possibilities is virtually endless. You may therefore struggle to choose what to learn next. In this part, we'll wrap up the series by pointing out some possible directions for future learning. After this, the final part will be a quiz on what we covered throughout the series.Read More…
  • Code
    Android SDK
    Android SDK: App DataAndroid preview@2x
    In this series, we are learning about Android SDK development from scratch. We have already become acquainted with the structure and basic elements in an Android application, including the resources, Manifest, and user interface. As soon as you start to develop functional apps for Android, you will need to store data of one kind or another. The Android platform offers a range of options for data storage in your apps, which we will examine in this tutorial.Read More…
  • Code
    iOS SDK
    Objective-C Succinctly: Data Types0e5ds8 preview image@2x
    Objective-C has two categories of data types. First, remember that Objective-C is a superset of C, so you have access to all of the native C data types like char, int, float, etc. Objective-C also defines a few of its own low-level types, including a Boolean type. Let's call all of these "primitive data types."Read More…