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.


Tutorial #13 - Using Some Preferences

Now that we have the core reading functionality working, we can start to add other features for the user.

One common thing in Android applications is to collect preferences from the user, tailoring the way the app behaves. In the case of EmPubLite, we will initially track two preferences:

In this tutorial, we will collect and use these two preferences.

This is a continuation of the work we did in the previous tutorial.

You can find the results of the previous tutorial and the results of this tutorial in the book’s GitHub repository:

Step #1: Defining the Preference XML Files

We need an XML resource file to define what preferences we wish to collect.

First, add four new <string> elements to res/values/strings.xml:

<string name="lastposition_title">Save Last Position</string>
<string name="lastposition_summary">Save the last chapter you were viewing and open up on that chapter when re-opening the app</string>
<string name="keepscreenon_summary">Keep the screen powered on while the reader is in the foreground</string>
<string name="keepscreenon_title">Keep Screen On</string>

Next, right click over res/ in your project, and choose New > “Android resource directory” from the context menu. Change the “Resource type” drop-down to be “xml”, then click OK to create the directory.

Then, right-click over your new res/xml/ directory and choose New > “XML resource file” from the context menu. Fill in pref_display.xml in the “New XML Resource File” dialog, then click OK to create the file.

This will open up in a preference screen editor, with “Design” and “Text” sub-tabs:

Android Studio Preference Screen Editor, As Initially Launched
Figure 302: Android Studio Preference Screen Editor, As Initially Launched

Drag a CheckBoxPreference from the Palette into the preview area. Then, in the Properties pane, set the key to saveLastPosition, set the title to @string/lastposition_title, and set the summary to @string/lastposition_summary:

Android Studio Preference Screen Editor, After First Preference
Figure 303: Android Studio Preference Screen Editor, After First Preference

Next, drag another CheckBoxPreference from the Palette into the preview area. Then, in the Properties pane for this newly-added preference, set the key to keepScreenOn, set the title to @string/keepscreenon_title, and set the summary to @string/keepscreenon_summary:

Android Studio Preference Screen Editor, After Second Preference
Figure 304: Android Studio Preference Screen Editor, After Second Preference

If you look at the XML in the “Text” sub-tab, you should see that it resembles:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">

  <CheckBoxPreference
    android:defaultValue="false"
    android:title="@string/lastposition_title"
    android:key="saveLastPosition"
    android:summary="@string/lastposition_summary" />
  <CheckBoxPreference
    android:defaultValue="false"
    android:title="@string/keepscreenon_title"
    android:key="keepScreenOn"
    android:summary="@string/keepscreenon_summary" />
</PreferenceScreen>

Step #2: Creating Our Preference Activity

We will eventually load that preference XML into a PreferenceFragment. We could use a PreferenceActivity for that, but we do not have enough preferences to warrant a full master/detail setup. Instead, we can just display the PreferenceFragment in a regular Activity, named Preferences, using a static inner class implementation of a PreferenceFragment, named Display.

Right-click over the com.commonsware.empublite package in your java/ directory and choose New > Activity > Empty Activity from the context menu. Set the activity name to be Preferences and uncheck all the checkboxes. Then click Finish to add the activity to the project.

In the Preferences class that is created, replace the current implementation with the following:

package com.commonsware.empublite;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;

public class Preferences extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getFragmentManager().findFragmentById(android.R.id.content)==null) {
      getFragmentManager()
        .beginTransaction()
        .add(android.R.id.content, new Display())
        .commit();
    }
  }

  public static class Display extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      addPreferencesFromResource(R.xml.pref_display);
    }
  }
}

If you prefer, you can view this file’s contents in your Web browser via this GitHub link.

Step #3: Adding To Our Action Bar

The preview of this section was accidentally identified as an Android 'tasty treat' by the Cookie Monster.

Step #4: Launching the Preference Activity

The preview of this section is in an invisible, microscopic font.

Step #5: Loading the Preferences

The preview of this section was last seen in the Bermuda Triangle.

Step #6: Saving the Last-Read Position

The preview of this section is [REDACTED].

Step #7: Restoring the Last-Read Position

The preview of this section is out seeking fame and fortune as the Dread Pirate Roberts.

Step #8: Keeping the Screen On

The preview of this section is off trying to sweet-talk the Khaleesi into providing us with a dragon.

In Our Next Episode…

The preview of this section is being chased by zombies.