We launched a new IT training category! Check out the 140+ courses now.

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

Defining preferences with Java

From: Android SDK: Local Data Storage

Video: Defining preferences with Java

I'm going to start by describing how to set preferences using Java code. I'm working in a version of my project called PreferencesWithJava. I've added a few user interface elements, an EditText object, and a couple of buttons, and the buttons are wired to methods in the main activity class using attributes in the XML layout file. Down here, in the button tags, each of the buttons has an onClick attribute. These are pointing to these methods, which I can jump to by holding down the Command key on Mac or the Control key on Windows and clicking on the method name.

Defining preferences with Java

I'm going to start by describing how to set preferences using Java code. I'm working in a version of my project called PreferencesWithJava. I've added a few user interface elements, an EditText object, and a couple of buttons, and the buttons are wired to methods in the main activity class using attributes in the XML layout file. Down here, in the button tags, each of the buttons has an onClick attribute. These are pointing to these methods, which I can jump to by holding down the Command key on Mac or the Control key on Windows and clicking on the method name.

Right now, these two methods are just outputting messages to the LOGCAT Console. I'll run the application in the emulator and then click the Set preferences button and the Show preferences button and show that my LOGCAT messages are appearing successfully. Notice that I've filtered my LOGCAT messages using a filter of tag: and then the tag name that I'm using in my log class calls. So now, let's take a look at the code that's needed to add and then retrieve preferences using Java code.

I'll go to my MainActivity class. As I mentioned previously, each preference that you save persistently is associated with a string-based key. I typically declare these keys as constants so I can refer to them successfully multiple times in my code. I'll start with the existing constant, the LOGTAG constant, and I'll duplicate that line of code. Then I'll change the new one so that the constant is USERNAME and the value is username in lowercase.

The constant name will be used to refer to the preference in Java code, while the lowercase value will be associated with the value when it's saved to disk. Next, I need a reference to something called a SharedPreferences object. The SharedPreferences class in the Android SDK represents a set of preferences that are saved as an XML file. They're exposed to you as a developer as a simple Java class that implements the map interface. I'll declare a private field, which is an instance of this class.

I'll type in the beginning of the class name, SharedPref, then I'll press Control+ Space and select the class from the list. And I'll name this object settings. Now, I'll instantiate the object by adding code to my onCreate method. The onCreate method is called automatically as the activity comes to the screen, so I'll initialize the value using settings =. Now, I have two choices. I can either call the getPreferences method, and that would return a reference to the preferences that are local to the current activity, or I can call the method getSharedPreferences and pass in a string identifier.

If you're working with preferences that will only be accessed by the current activity, call getPreferences. If you're working with preferences that will be shared through the entire application, call getSharedPreferences. I'll call the getPreferences method, and I'll pass in a mode of MODE_PRIVATE. That means that the preferences are local to the application. As I mentioned in earlier video, as of Jelly Bean, you can't share preferences between multiple apps, but that capability might come about in future versions.

So now I have a reference to my settings object and I can use that anywhere in the activity. I'll go down toward the bottom of the class and I'll add some code to my setPreference method. To set a preference, you need something called a SharedPreferences editor object. The editor object is a class that's a field of SharedPreferences. So, I'll type in SharedPreferences, then a dot, and I'll choose the SharedPreferences.Editor class. And I'll name this object editor and I'll get its reference by calling the settings objects edit method.

This returns a reference to the editor object for the current preferences file. Now, I need a value to put into the preferences. To make it a little bit easier to work with my user interface, I've added a class to this project called UIHelper. You can find it in the Util subpackage. This class has methods to manipulate and get values from various user interface elements, including textViews, edit text, and check boxes. I'm going to be using the displayText and getText methods in this exercise.

I'll go back to my MainActivity class and down to my setPreference method, and I'll expand to full screen. And I'll create a new string variable called prefValue, and I'll get that value by calling UIHelper.getText. I'll pass in this as the current activity and then the resource ID of the user interface element from which I want to get the text. That will be R.i.d.editText1.

That's the I.D. of the editText object in my current layout. So now I have a value, and I'll add it to my preferences by calling the editor object and one of its put methods. The editor object has these six put methods. You can add a Boolean value, a numeric value as a float integer or long, or a string. Or if you want to save multiple strings as a set, you call putStringSet. I'll add a single string value by calling putString. I'll set the key to the USERNAME constant that I defined at the top of the class, and I'll pass in the prefValue as the preference value.

I could now add more preferences, but I don't have any more for this exercise, so I have only one more critical step, and that's to commit my changes. I'll call editor.commit and that saves the values to persistent storage. I'll also give the user some visual feedback. Once again, I'll call my UIHelper class, and this time I'll display some text. I'll pass in this as the activity, R.i. d.textView1 as the ID of the textView object, and then a literal string of Preference saved.

I'll save those changes, and now I'll run the application in the emulator by pressing my keyboard shortcut. That's Command+Shift+F11 on Mac. When the application comes to the screen, I'll type in my name as the preference value and I'll click Set preferences. And I see the feedback that the preference was saved. But now, I'll add code to retrieve and display the preference value. I'll go back to the main activity class, and now I'll add code to the refreshDisplay method.

I'll declare a string variable that I'll call prefValue, and I'll get its value by calling a method of my settings object. I'll call settings.get. Just as with the put methods of the editor object, there are versions of the get method for each supported data type, plus one called getAll that returns all of the values in the current object as a map object. I'll call getString, and I'll pass in my USERNAME constant as the key, and then I'm asked for a default value.

I'll type a literal of Not found, and if there is no preference with this key, that's the value that I'll get back. Now, to display the value once again, I'll use my UIHelper class. This time I'll use displayText, and I'll pass in this as the activity, R.i.d.textView1 as the ID of the textView object, and then prefValue as the value I want to display. I'll save and run the application again and when it refereshes, I'll click Show preferences without setting the value again.

This demonstrates that the value has been saved to persistent storage. It will persist between launches of the application and even after a device has been powered down and then powered back up again. At a later point, if I want to restore to a blank slate--that is, delete all of my personal data--I can go to the Home screen, then from there to the application list, I can click on the application icon, and drag it up to App info.

Once the emulator has finished calculating the amount of data that's been used, I can click Clear data and all of the application's data will be completely deleted. I can then go back to the application and run it again, and when I click on Show preferences, I get Not found. I'll type in my name and click Set preferences, I'll leave the activity, I'll start it up again, I'll click Show preferences, and show that once again the value has been saved persistently.

So, that's all the code you need to work with preferences using pure Java. Again, you determine whether preferences are local to the activity or shared with the entire application by which method you call-- GetPreferences or GetSharedPreferences--and from that point forward, the code is exactly the same to get and retrieve values to use in your application.

Show transcript

This video is part of

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

29 video lessons · 6138 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 preferences from 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.