Home > Android > Creating and Saving Preferences

Creating and Saving Preferences


Creating and Saving Preferences

To create or modify a Shared Preference, call getSharedPreferences on the application Context, passing in the name of the Shared Preferences to change.
Shared Preferences are shared across an application’s components but aren’t available to other applications.

To modify a Shared Preference, use the SharedPreferences.Editor class. Get the Editor object by
calling edit on the SharedPreferences object you want to change. To save edits, call commit on the Editor,
as shown in the code snippet below.

public static final String MYPREFS = “mySharedPreferences”;
protected void savePreferences(){
// Create or retrieve the shared preference object.
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean(“isTrue”, true);
editor.putFloat(“lastFloat”, 1f);
editor.putInt(“wholeNumber”, 2);
editor.putLong(“aNumber”, 3l);
editor.putString(“textEntryValue”, “Not Empty”);
// Commit the changes.
editor.commit();
}

Retrieving Shared Preferences

Accessing saved Shared Preferences is also done with the getSharedPreferences method. Pass in the name of the Shared Preference
you want to access, and use the type-safe get<type> methods to extract
saved values.
Each getter takes a key and a default value (used when no value is available for that key), as shown in
the skeleton code below:

public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean(“isTrue”, false);
float lastFloat = mySharedPreferences.getFloat(“lastFloat”, 0f);
int wholeNumber = mySharedPreferences.getInt(“wholeNumber”, 1);
long aNumber = mySharedPreferences.getLong(“aNumber”, 0);
String stringPreference;
stringPreference = mySharedPreferences.getString(“textEntryValue”,
“”);
}

Source : Professional Android Application Development

Categories: Android
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: