The following is the first few sections of a chapter from The Busy Coder's Guide to Android Development, plus headings for the remaining major sections, to give you an idea about the content of the chapter.
Android has many different ways for you to store data for long-term use by your
activity. The simplest ones to use are
SharedPreferences and simple files.
Android allows activities and applications to keep preferences, in the form of
key/value pairs (akin to a
Map), that will hang around 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 primitive value (
Preferences can either be for a single activity or shared among all activities in an application. Other components, such as services, also can work with shared preferences.
To get access to the preferences, you have three APIs to choose from:
getPreferences()from within your
Activity, to access activity-specific preferences
getSharedPreferences()from within your
Activity(or other application
Context), to access application-level preferences
PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
The first two take a security mode parameter. The right answer here is
MODE_PRIVATE, so no other applications can access the file. The
getSharedPreferences() method also takes a name of a set of preferences;
getPreferences() effectively calls
getSharedPreferences() with the
activity’s class name as the preference set name. The
getDefaultSharedPreferences() method takes the
Context for the preferences
All of those methods return an instance of
SharedPreferences, which offers a
series of getters to access named preferences, returning a suitably-typed
getBoolean() to return a boolean preference). The getters also
take a default value, which is returned if there is no preference set under the
Unless you have a good reason to do otherwise, you are best served using the
third option above —
getDefaultSharedPreferences() — as that will give
SharedPreferences object that works with a
default, as will be described later in this chapter.
The preview of this section left for Hollywood to appear in a reality TV show.
The preview of this section is en route to Mars.
The preview of this section took that left turn at Albuquerque.
The preview of this section will not appear here for a while, due to a time machine mishap.