O'Reilly logo

Android Application Development For Dummies, 2nd Edition by Donn Felker, Michael Burton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required