New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

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

Using preferences in Android apps

From: Android SDK: Local Data Storage

Video: Using preferences in Android apps

The simplest and smallest sort of data that you can store persistently on disk in an Android app is called a preference. There are a couple of different ways of creating preferences in an application, and they are sometimes referred to as simply preferences and sometimes as shared preferences. You can initialize preferences either in Java code or through a preference activity--a visual interface that you create just like you do any activity. Each preference value is a simple key-value pair.

Using preferences in Android apps

The simplest and smallest sort of data that you can store persistently on disk in an Android app is called a preference. There are a couple of different ways of creating preferences in an application, and they are sometimes referred to as simply preferences and sometimes as shared preferences. You can initialize preferences either in Java code or through a preference activity--a visual interface that you create just like you do any activity. Each preference value is a simple key-value pair.

The keys are always strings, but the values can have one of a number of different types, including Booleans, integers, longs, floats, and strings. It's also possible to create a single preference value that consists of multiple strings that are typed as a Java set. You can create your preferences in Java by using a class called SharedPreferences. You start by creating an instance of this class. Whenever you create a SharedPreferences object, you always assign a mode, and the most common is called MODE_PRIVATE.

This means that the preferences in this set will be private to the current application and are only accessible with the application that has this current package. There are other mode constants available in the API, such as MODE_WORLD_WRITABLE, but as of Jelly Bean-- that's Android 4.2--sharing of preferences between apps isn't currently supported. There's a note in the API docs to this effect. That capability might be supported in the future versions.

When you create a set of preferences, you indicate whether the preferences are private to the current activity or shared between multiple activities, and you do this by assigning a name. If you call the getPreferences method and simply pass in MODE_PRIVATE, you're saying, create a set of preferences that are unique to the current activity. If you call getSharedPreferences, then you have to pass in an explicitly activity-set name as a string, and then you can reuse that name from other activities and get to those same values.

If you call getPreferences, there's still a name associated with that set. It's the name of the current activity. But the intention is that those are private to the activity and that anything you call with getSharedPreferences are shared with the entire application. You can also choose to initialize your preferences using an activity. The advantage of preference activities is that they handle all the creating of the values and writing them to disk automatically for you. You don't have to assign a name because preferences that are created through an activity are always available to the entire application.

There's amore limited set of data types that you can use with preferences created in this way. These values can be Boolean, strings, or list of strings. You can't easily create integers, floats, or longs. In order to create a preference activity, you'll define it in a layout file. The code in these layout files will look similar to the layout files used to create your own custom activities, but the names of the elements are strictly defined. Once you've defined the preference activity, you can navigate to it using exactly the same sort of a code that you would with any activity: by creating an intent and then asking to go to that activity through the intent.

You'll see some differences in how activities are created, depending on what version of the SDK you're targeting. Prior to Android 3, Honeycomb, a preference activity was created in single XML file. Starting in Honeycomb, and continuing through Jelly Bean, you can use the Fragment API and put together a preference activity using one or more fragments that are then pieced together at runtime. I'll show you both approaches to creating preferences--defining them through pure Java code or defining them through an activity--and then show you how to read those preferences into memory and how to listen for changes to preferences that might happen at runtime.

As you decide how to put preferences to work in your application, here are two very important things to know about them. First of all, preference values are not encrypted. They're stored to your Android devices persistent storage as simple unencrypted XML files. And that means that you should never store sensitive information that you haven't explicitly encrypted. The second thing is that preferences can be easily deleted by the user. The user can go on to the Settings app or into the application list and say that they want to remove application data and it will be completely wiped from persistent storage and won't be recoverable.

So in using preferences in you application, make sure that your app knows how to get started from scratch if the preferences don't already exist. I'll be showing you how to code for preferences so that when you read a preference, you can always provide a default value, a value that you work with if in fact the preference has never been set or has been previously set and then deleted. So let's get started learning how to code with preferences, both in Java and with the preference activity.

Show transcript

This video is part of

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

29 video lessons · 5475 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

Are you sure you want to delete this note?

No

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.