Friday, February 10, 2012

How to store and retrieve preferences in an Android app?

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 Activity.getPreferences() with no name to keep them private to the calling activity. You cannot share preferences across applications (except by using a content provider). 

This example has been provided by from 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();
    }
}

No comments:

Post a Comment