Search this blog

How to access Application Preferences in Android

Android provides you to retrieve shared application preferences by using the getSharedPreferences() method of the application context. You can use the SharedPreferences class to save simple application data, such as configuration settings.

You can give each SharedPreferences object a name, allowing you can organize preferences into categories or store preferences all together in one large set.

For example, you might want to keep track of each user’s name and some simple game state information, such as whether the user has credits left to play. The given below code creates a set of shared preferences called gampre and saves a few such preferences:

SharedPreferences settings = getSharedPreferences(“gampre”, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString(“UserName”, “Spunky”);
prefEditor.putBoolean(“HasCredits”, true);

Now to retrieve preference settings, you simply retrieve SharedPreferences and read the desired values back out:

SharedPreferences settings = getSharedPreferences(“gampre”, MODE_PRIVATE);
String userName = settings.getString(“UserName”, “Chippy Jr. (Default)”);


Post a Comment