Using Preferences

Android allows apps to keep preferences, in the form of key/value pairs (akin to a Map), that will persist between invocations of an activity. As the name suggests, the primary purpose is for you to store user-specified configuration details, such as the last feed the user looked at in your feed reader, or what sort order to use by default on a list, or whatever. Of course, you can store in the preferences whatever you like, so long as it is keyed by a String and has a rudimentary value (boolean, String, etc.)

The principal use of SharedPreferences, though, is for storing data that is collected by a preference UI. Android provides a system for producing a UI that looks a lot like the individual screens of the Settings app. That UI is fairly easy to set up and is a recommended solution for configuration options and related settings.

In this chapter, we will examine how to set up a preference UI and work with SharedPreferences

The Preferred Preferences

The good news is that there is only one SharedPreferences class.

The bad news is that there are a few implementations of the preference UI. The native one — classes in android.preference — has been deprecated. Instead, we are supposed to use the AndroidX implementation.

The SimplePrefs sample module in the Sampler and SamplerJ projects use the AndroidX implementation, in the form of the androidx.preference:preference library. This sample app offers a preference UI (PrefsFragment) and a regular UI that shows the current value of the user-supplied preferences (HomeFragment).


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.