Chapter 9. Share Preference
Chapter 9. Share Preference
Chapter 9. Share Preference
Shared Preference
Note
This slide is based on Google Android code labs
slides
Original slides:
https://drive.google.com/drive/folders/1eu-LXxiHoc
SktGYpG04PfE9Xmr_pBY5P
2
9.1 Shared Preferences
3
Contents
● Shared Preferences
● Listening to changes
4
What is Shared Preferences?
6
Shared Preferences vs. Saved Instance State
7
Creating Shared Preferences
● Need only one Shared Preferences file per app
● Name it with package name of your app—unique
and easy to associate with app
● MODE argument for getSharedPreferences() is for
backwards compatibility—use only
MODE_PRIVATE to be secure
8
getSharedPreferences()
9
Saving Shared Preferences
● SharedPreferences.Editor interface
● Takes care of all file operations
● put methods overwrite if key exists
● apply() saves asynchronously and safely
10
SharedPreferences.Editor
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.putInt("count", mCount);
preferencesEditor.putInt("color", mCurrentColor);
preferencesEditor.apply();
}
11
Restoring Shared Preferences
● Restore in onCreate() in Activity
● Get methods take two arguments—the key, and
the default value if the key cannot be found
● Use default argument so you do not have to test
whether the preference exists in the file
12
Getting data in onCreate()
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
if (savedInstanceState != null) {
mCount = mPreferences.getInt("count", 1);
mShowCount.setText(String.format("%s", mCount));
13
Clearing
● Call clear() on the SharedPreferences.Editor and
apply changes
SharedPreferences.Editor preferencesEditor
=
mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
15
Listening to
Changes
16
Listening to changes
● Implement interface
SharedPreference.OnSharedPreferenceChangeLi
stener
callback
Interface and callback
public class SettingsActivity extends AppCompatActivity
implements OnSharedPreferenceChangeListener { ...
18
Creating and registering listener
SharedPreferences.OnSharedPreferenceChangeListener listener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(
SharedPreferences prefs, String key) {
// Implement listener here
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
19
You need a STRONG reference to the listener
22
What's Next?
23
END
24