Android Projects

Android Development Books

Thursday

Application Preferences in android


Android applications can store data in application preferences. In this tutorial, you learn how to store persistent application data with shared preferences.

The Android SDK provides helpful APIs for storing and retrieving application preferences. Preferences are stored as groups of key/value pairs and are available at the Activity level or shared across all of Activity classes for a given application (but not outside of the application package).

What Is A Preference?

Shared preferences are simply sets of data values that are stored persistently. By persistence, we are talking about data that persists across application lifecycle events. In other words, the application (or device, for that matter) can be started and stopped without losing the data. The next time the user launches the application, that data will still be available.
An individual preference is simply a key-value pair with a specific data type for the value. The preference key is simply a string that uniquely identifies the preference and the value is just that: the value of that preference.
For example, your application might want to store the user’s name. The application could have a single preference to store this information:
  • The data type of the preference could be a String
  • The key could be a string called “UserName”
  • The value would be the actual username string, such as “AndroidPowerUser123” or “Bob”
A preference can be any of a number of different data types. The following data types are supported by the SharedPreferences class:
  • Boolean values
  • Float values
  • Integer values
  • Long values
  • String values

How Shared Preferences Work

The Android SDK includes helpful classes for getting application preferences up and running easily. Preference functionality can be found in the SharedPreferences interface of the android.content package.
An application can have multiple sets of application preferences, where each set has a name. For example, a game application might have a set of preferences for user information (user name, email, high score, etc.) and a set of preferences for game state (current level, current score, etc.). Preferences can be stored at the activity or application level.
Application-level preferences are available across all activities. These preferences are retrieved using the application Context class method called getSharedPreferences() by name. For example:
  1. import android.content.SharedPreferences;  
  2. …  
  3. SharedPreferences settings =  
  4.     getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  
There is no limit to the number of sets of shared preferences your application can have. How your application organizes its preferences is up to you. However, you may want to declare your preference set names so that you can easily load and access the preferences from any Activity within your application. For example:
  1. public static final String PREFERENCE_FILENAME = "AppGamePrefs";  
An activity can also have private preferences. These preferences are only available within the specific Activity class and are not shared with other activities. An activity can only have one set of private preferences. The following code retrieves the activity’s private preferences:
  1. import android.content.SharedPreferences;  
  2. …  
  3. SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);  

Setting Preferences

Once you have a valid SharedPreferences object, you must use a SharedPreferences.Editor to add, modify, or delete preference content. To retrieve an Editor for a specific SharedPreferences object, use its edit() method. Make any changes to the preferences using the methods available in the Editor class. For example, the SharedPreferences.Editor class has helper methods for saving preferences of different data types:
Saving preferences to your application is fairly straightforward. First, you must decide if you want application or activity preferences. Use the appropriate method to retrieve the appropriate SharedPreferences object: use the getPreferences() method of the Activity class for activity-level preferences or the getSharedPreferences() method of the Context class for application-level preferences.
  • Store boolean values with the putBoolean() method
  • Store float values with the putFloat() method
  • Store int values with the putInt() method
  • Store long values with the putLong() method
  • Store String values with the putString() method
Within the Editor, you can also remove a specific preference by name using the remove() method, or remove all preferences within the set using the clear() method. Once you’ve finished editing the SharedPreferences object, you can save your changes using the Editor’s commit() method.
For example, the following code retrieves a set of application preferences called “MyGamePreferences” and adds a string preference called “UserName” with a value of “Guest123” and a Boolean preference called “PaidUser” with a value of false.
  1. import android.content.SharedPreferences;  
  2. …  
  3. SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  
  4. SharedPreferences.Editor prefEditor = gameSettings.edit();  
  5. prefEditor.putString("UserName""Guest123");  
  6. prefEditor.putBoolean("PaidUser"false);  
  7. prefEditor.commit();  

Updating Preferences

Updating preferences is as simple as retrieving another SharedPreferences.Editor and making changes to a given preference by name. For example, the following code modifies the “PaidUser” preference:
  1. SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  
  2. SharedPreferences.Editor prefEditor = gameSettings.edit();  
  3. prefEditor.putBoolean("PaidUser"true);  
  4. prefEditor.commit();  
Tip: As you can see, it can be useful to define each preference key as static final string variables so that a given preference is always stored in a regular, reproducible fashion. You don’t want random preference strings floating around in your code.

Retrieving Preferences

You don’t need an Editor to simply read preferences. Instead, retrieve the SharedPreferences object and use the appropriate method to retrieve a preference by name:
  • Retrieve boolean values with the getBoolean() method
  • Retrieve float values with the getFloat() method
  • Retrieve int values with the getInt() method
  • Retrieve long values with the getLong() method
  • Retrieve String values with the getString() method
Each of these methods has two parameters: the preference key string and a default value to return if the preference is undefined.
You can also check for the existence of a preference by name using the contains() method. You can also iterate through all preferences for a given set using the getAll() method of the SharedPreferences class.

Reacting to Preference Changes

Your application can listen for, and react to, changes to shared preferences by implementing a listener and registering it with the specific SharedPreferences object using the registerOnSharedPreferenceChangeListener() and unregisterOnSharedPreferenceChangeListener() methods.

Conclusion

Shared preferences (android.content.SharedPreferences) can be used to easily store application data. Application preferences are stored as key-value pairs, and can be many different data types, including numbers, strings and Boolean values. Different sets of preferences can be stored in named preference sets. Use shared preferences to store simple application data in a persistent manner.
if you want more inforamtion about this article click here
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

1 comments

  1. I have no words for this great post such a awe-some information i got gathered. Thanks to Author.

    ReplyDelete

Thanks for your comment

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

Related Posts Plugin for WordPress, Blogger...
© Google Android Lovers
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0