Getting What You Want

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

• getDefaultSharedPreferences(), on PreferencesManager, to get the shared preferences that work in concert with Android's overall preference framework

The first two take a security-mode parameter—for now, pass in 0. 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 (e.g., your Activity).

All of those methods return an instance of SharedPreferences, which offers a series of getters to access named preferences, returning a suitably typed result (e.g., getBoolean() to return a Boolean preference). The getters also take a default value, which is returned if there is no preference set under the specified key.

0 0

Post a comment