Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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.
Get unlimited access to all courses for just $25/month.Become a member
61 Video lessons · 92675 Viewers
82 Video lessons · 104181 Viewers
71 Video lessons · 75783 Viewers
56 Video lessons · 107160 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
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.
Your file was successfully uploaded.