Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types. It is typically used to store application preferences, such as a default greeting or a text font to be loaded whenever the application is started. Call Context.getSharedPreferences() to read and write values. Assign a name to your set of preferences if you want to share them with other components in the same application, or use Activitv.getPreferencesn with no name to keep them private to the calling activity. You cannot share preferences across applications (except by using a content provider).

Here is an example of setting user preferences for silent keypress mode for a calculator:

// Restore preferences

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent);

@Override protected void onStop(){ super.onStop();

// Save user preferences. We need an Editor object to // make changes. All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS NAME, 0);

SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode);

// Don't forget to commit your edits!!! editor.commit();

0 0

Post a comment