O'Reilly logo

Android™ Tablet Application Development For Dummies® by Donn Felker

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 Run Time

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

In the Task Reminder application, you need to read these values in the ReminderEditActivity 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 ReminderEditActivity and navigate to the populateFields() method. This method determines whether the task is an existing task or a new task. If the task is new, you will pull the default values from SharedPreferences and load them into the activity for the user. If for some reason the user has never set the preferences, these default values will be empty strings, and you will ignore them. In short, you will only use the preferences if the user has set them.

To retrieve the preference values, you need to use the SharedPreferences object, as shown in Listing 17-3. In the populateFields() method, add the bolded code as shown in Listing 17-3.

Listing 17-3: Retrieving Values from SharedPreferences

private void populateFields() { if (mRowId != null) { Cursor reminder = mDbHelper.fetchReminder(mRowId); startManagingCursor(reminder); mTitleText.setText(reminder.getString( ...

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