ITEEDU

Using Application Preferences

You can store application preferences such as a default greeting or text font to be loaded whenever this 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 package, or use Activity.getPreferences() with no name to keep them private to the calling activity. You cannot share preferences across packages. Here is an example of setting user preferences for silent keypress mode for a calculator.

public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
     ...      

    @Override
    protected void onCreate(Bundle state){         
       super.onCreate(state);
    
    ...
    
       // 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();
    }
}