Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Defining shared preferences with an activity

From: Android SDK: Local Data Storage

Video: Defining shared preferences with an activity

In a previous video, I described how to set user preferences using Java code. Now, I'll show you how to create a PreferenceActivity, a user interface that lets the user type in values and save those values to persistent storage automatically. I'll be using a version of my project called Preference Activity that still has the buttons to set and show preferences but now no longer has an EditText control. I'll be handling user input through my new activity. I'll start by creating a new layout.

Defining shared preferences with an activity

In a previous video, I described how to set user preferences using Java code. Now, I'll show you how to create a PreferenceActivity, a user interface that lets the user type in values and save those values to persistent storage automatically. I'll be using a version of my project called Preference Activity that still has the buttons to set and show preferences but now no longer has an EditText control. I'll be handling user input through my new activity. I'll start by creating a new layout.

In the menu, I'll select File > New > Android XML file. I'll set the Resource Type to Preference, and then I'll give the file a name of settings. The .xml extension will be added automatically, and the new file will be saved into an XML subfolder underneath my Resources Area. I'll click Next, and I'll accept all the defaults here and click Finish. That creates my new XML file. The file might open to this view--the XML view--or might open to the Structure view.

I'm going to start in the Structure view and add elements and categories here. When you add up preference to this screen, you can either group it within a category or edit directly to the screen's root. I'll start with the category. With the screen selected, I'll click the Add button and I'll choose Preference Category and click OK. I'll set the category's attributes. I'll click Attributes from Preference. I'll set a title-- That's what the user will see--and I'll use a title of General settings.

Now I'm ready to add preferences. I'll click back on the category element and click Add again. You can add a CheckBoxPreference for a Boolean preference, an EditText for a single string, or one of the list controls for the sets of strings. I'll start with an EditTextPreference for the user name. I'll select that item and click OK and then open up the Attributes. The Key is a string that you'll use in your Java code to address this preference. I'll use a string of pref_username.

The Title is a string that the user will see on the screen, and I'll type in User name. The Summary is a string that you can add also, and if you set it, it will be visible to the user and this can be used to describe what the preference is used for. I'll leave the Summary and all of the other values blank and I'll go on to create another preference. I'll go back to the category and click Add again, and this time I'll use a CheckBoxPreference. I'll go to the attributes and I'll set the Key for this one to pref_viewimages.

I'll set the title to View images, and I'll set the Summary to a string of Determines whether tours are shown with images. I'll click back on the tree and that refreshes its view. Then I'll go to the XML view. I'll double-click the tab to expand to full screen, and then I'll reformat so it's a little bit more readable. I'll press Command+A--that's Ctrl+A on Windows to select all--and then Command+I or Ctrl+I on Windows and that reformats the XML layout.

So this is what your XML looks like. The category is a child of the screen and each preference is a child of the category. And again, the category is optional. I'll save those changes. My layout is done. Now, I'm ready for the next step. Just as when you create an activity for some functionality in your application, you need to create a Java class that will use this layout. I'll go to my Package Explorer. I'll go to my default package, and I'll create a new Java class.

I'll name this class SettingsActivity, and I'll set the Superclass to a class named PreferenceActivity. This is a class that's a part of the Android SDK. And I'll click Finish. Just as when creating any activity, you have to bind the activity class to the activity layout. I'll move the cursor into the class declaration and create a little bit of space, and then I'll override the onCreate method. I'll type the beginning of the method name and press Ctrl+Space and select onCreate.

Within the new onCreate method, I'll delete that TODO comment, and then after the call to the Superclass's onCreate method, I'll call addPreferencesFromResource, and I'll pass in the resource ID of the new layout XML file I've just created. That will be R.xml.settings. Now, when this activity is brought to the screen, the settings layout will be presented. Notice that you're getting a warning indicating that the addPreferencesFromResource method is deprecated.

That's because in this version of the SDK--I'm starting back in Honeycomb-- the SDK prefers that you use something called the Fragment API to put together your preference activities. This approach, however, will still work all the way back to older versions of Android, all the way back to 1.X. So I'm going to use this code for now, but this is an interesting warning to keep track of, because the addPreferencesFromResource method might go away in future versions. For the moment though, I'll get rid of this warning.

I'll go to the icon on the left. I'll click it and select addSuppressWarnings, and that gets rid of the warning icon. The addPreferences method name is still struck out, and that will be a useful warning to me in the future. I'll save those changes. That's all I need to do for the Java class. Next, I need to register the activity in my Application Manifest. I'll open AndroidManifest.xml. It might open in the Manifest view or it might open in the XML view.

I'll go to the XML view and expand to full screen. Just as with any activity, you have to register the Java class in the manifest. I'll move the cursor past the one and only activity--that's the MainActivity-- and I'll create a new activity tag. I'll assign a name attribute, and I'll set it to the name of my class, starting with a period representing the default package and then the name of the class, SettingsActivity.

I'll complete the tag and that adds the end tag, and that's all I need to do. I don't need to add filters or anything else. Now the activity is a part of the application. I'll save those changes. I have one more step. I need to add code to the MainActivity class so that when the user says they want to look at the settings, I launch this new PreferenceActivity. So I'll go to my MainActivity.java class. I'll expand that to full screen, and I'll go down to my setPreference method, which in this version of the application now doesn't have any useful code.

Within the setPreference method I'll create a new intent object. I'll declare it with the Intent class and name it intent, and I will instantiate it using the intent class constructor new Intent. I'll pass in this as the parent and the name of my settings class, SettingsActivity, and the .class extension. So now I have an intent object that will launch the class, and I'll call start activity, and I'll pass in the intent object.

The set preference method is still being triggered by touching the button. So now, instead of grabbing a value from a user interface element and EditText, it will launch the activity. I'll save my changes and I'll run my application. Now, to launch my new activity, I just click the Set preferences button. That opens my new activity. I can click on the User name and type in a value and then click OK. I can click the check box to set the View images value to either true or false.

Now I need to modify some code so I can retrieve those settings. I'll go back to my Java class and show that I already have code that's looking for the user name. There are a couple of things I need to change to make this work. First of all, in the onCreate method, instead of referencing the getPreferences method, which returns an instance of a preferences object local to the activity, I'll use a class called PreferenceManager. I'll call its method, getDefaultSharedPreferences, and pass in this.

That returns a reference to the preferences object that's created by the preference activity. Now, I can get to those preferences easily. Next, I need to change the constant for the user name to match what I set as the preference key in my preference activity. I'll go up here and change user name to pref_username. While I'm here, I'll add another constant for the View images preference. I'll use a constant of VIEWIMAGE, and I'll set it to pref_viewimages.

That takes care of the user name, but I also need to add code to update my check box, so I'll go down here and I'll type in UIHelper.setCBChecked. That's my custom static method that will manage a check box in my user interface. I'll pass in this for the activity, R.id.checkBox1 for the check box I want to update, and settings.getBoolean. I'll pass in VIEWIMAGE as the key I want to look up and false as the default.

Now I'm ready to test again. I'll relaunch the application in the emulator, and once the application opens, I'll click Show preferences and that retrieves both the user name and the Boolean value for view images, and updates my user interface. So those are the steps for creating a preference activity: create the activity layout, create the Java class that uses the layout, register the Java class in your manifest, and then open the activity at runtime by creating intent and starting the activity.

You can then retrieve the preferences at runtime by calling the Preferencemanager.getDefaultSharedPreferences method, and that returns the instance of the preferences object that's managed by the activity.

Show transcript

This video is part of

Image for Android SDK: Local Data Storage
Android SDK: Local Data Storage

29 video lessons · 5675 viewers

David Gassner
Author

 
Expand all | Collapse all
  1. 6m 34s
    1. Welcome
      50s
    2. What you should know before starting this course
      2m 11s
    3. Using the exercise files
      3m 33s
  2. 21m 6s
    1. Exploring local data storage options
      5m 58s
    2. Configuring Eclipse and the Android Developer Tools
      5m 29s
    3. Creating an Android virtual device
      3m 23s
    4. Creating a new Android project
      6m 16s
  3. 31m 30s
    1. Using preferences in Android apps
      5m 28s
    2. Defining preferences with Java
      9m 31s
    3. Defining shared preferences with an activity
      10m 50s
    4. Listening for changes to shared preferences
      5m 41s
  4. 51m 13s
    1. Creating and reading files in internal storage
      10m 18s
    2. Creating and reading JSON data files
      9m 48s
    3. Working with files in external storage
      11m 22s
    4. Parsing a read-only XML file with XmlPullParser
      11m 46s
    5. Parsing a read-only XML file with JDOM
      7m 59s
  5. 1h 8m
    1. Creating a new SQLite database
      2m 52s
    2. Defining a database with SQLiteOpenHelper
      12m 12s
    3. Managing the database with a DataSource class
      9m 38s
    4. Inserting data into a database table
      10m 29s
    5. Retrieving and displaying data
      11m 44s
    6. Importing data from XML to SQLite
      5m 15s
    7. Filtering and sorting data
      9m 27s
    8. Accessing a database from the command line
      6m 46s
  6. 42m 0s
    1. Improving the data display
      9m 29s
    2. Passing user-selected data to a detail activity
      11m 36s
    3. Working with multiple database tables
      10m 28s
    4. Deleting data from database tables
      10m 27s
  7. 49s
    1. Where to go from here
      49s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Android SDK: Local Data Storage.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.