2015-05-17

[Android] 讀寫SharedPreference. Read and Write SharedPreference

This is a simple note for reading and writing Android SharedPreference.

Reference:
https://developer.android.com/guide/topics/data/data-storage.html#pref
https://developer.android.com/reference/android/content/SharedPreferences.html



1. define a name for the SharedPreference file

public static final String PREFS_NAME = "MyPrefsFile";


2. define a name for each column of the SharedPreference

public static final String PREFS_KEY_BOOLEAN_SILENT = "silentMode";

3. Read data from SharedPreference

// Read preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(PREFS_KEY_BOOLEAN_SILENT, false);

4. Write data to SharedPreference

boolean mSilentMode = true;

// Write preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(PREFS_KEY_BOOLEAN_SILENT, mSilentMode);
/* put other columns to SharedPreference before commit */
// Commit the edits!
editor.commit();