Working with Preferences in Your Activities at Runtime

Though setting preferences in a PreferenceActivity is useful, it provides no value in the end unless you can read the preferences from the SharedPreferences object at runtime and use them in your application. Thankfully, Android makes the process fairly simple.

In the Task Reminder application, you read these values in the Reminder EditFragment to set the default values when a user creates a new task. Because the preferences are stored in SharedPreferences, you can access the preferences across various activities in your application.

Retrieving preference values

Open the ReminderEditFragment and navigate to the onCreateView() method. It determines whether the task is an existing task or a new task. If the task is new, you pull the default values from SharedPreferences and load them into the activity for the user. If for some reason the user has never specified her preferences, they’re empty strings and you ignore the defaults. You use the preferences only if the user has set them.

To retrieve preference values, you use the SharedPreferences object, as shown in Listing 15-3. Add the bold code to the very bottom of onCreate View().

Listing 15-3: Retrieving Values from SharedPreferences

if (mRowId == 0) { 1

// This is a new task - add defaults from preferences if set.

SharedPreferences prefs = PreferenceManager 3

.getDefaultSharedPreferences(getActivity());

String defaultTitleKey = getString(R.string.pref_task_title_key); ...

Get Android Application Development For Dummies, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.