Chapter 9. Share Preference

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 24

Mobile Programing

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?

● Read and write small amounts of primitive data as


key/value pairs to a file on the device storage
● SharedPreference class provides APIs for
reading, writing, and managing this data
● Save data in onPause()
restore in onCreate()
5
Shared Preferences and Saved Instance State

● Small number of key/value pairs


● Data is private to the application

6
Shared Preferences vs. Saved Instance State

● Persist data across user sessions, ● Preserves state data across


even if app is killed and restarted, activity instances in same user
or device is rebooted
session
● Data that should be remembered
● Data that should not be
across sessions, such as a user's
remembered across sessions,
preferred settings or their game
such as the currently selected
score
tab or current state of activity.
● Common use is to store user
● Common use is to recreate state
preferences
after the device has been rotated

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()

private String sharedPrefFile =


"com.example.android.hellosharedprefs";
mPreferences =
getSharedPreferences(sharedPrefFile,
MODE_PRIVATE);

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));

mCurrentColor = mPreferences.getInt("color", mCurrentColor);


mShowCount.setBackgroundColor(mCurrentColor);

mNewText = mPreferences.getString("text", "");


} else { … }

13
Clearing
● Call clear() on the SharedPreferences.Editor and
apply changes

● You can combine calls to put and clear. However,


when you apply(), clear() is always done first,
regardless of order!
14
clear()

SharedPreferences.Editor preferencesEditor
=
mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
15
Listening to
Changes

16
Listening to changes
● Implement interface
SharedPreference.OnSharedPreferenceChangeLi
stener

● Register listener with


registerOnSharedPreferenceChangeListener()
● Register and unregister listener in onResume()
and onPause()
● Implement on onSharedPreferenceChanged() 17

callback
Interface and callback
public class SettingsActivity extends AppCompatActivity
implements OnSharedPreferenceChangeListener { ...

public void onSharedPreferenceChanged(


SharedPreferences sharedPreferences, String key) {
if (key.equals(MY_KEY)) {
// Do something
}
}
}

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

● When registering the listener the preference


manager does not store a strong reference to the
listener
● You must store a strong reference to the listener,
or it will be susceptible to garbage collection
● Keep a reference to the listener in the instance
data of an object that will exist as long as you
need the listener
20
Practical: HelloSharedPrefs

● Add Shared Preferences to a


starter app

● Add a "Reset" button that clears


both the app state and the
preferences for the app
21
Learn more
● Saving Data
● Storage Options
● Saving Key-Value Sets
● SharedPreferences
● SharedPreferences.Editor
Stackoverflow
● How to use SharedPreferences in Android to store, fetch and edit values
● onSavedInstanceState vs. SharedPreferences

22
What's Next?

● Concept Chapter: 9.1 Shared Preferences


● Practical: 9.1 Shared Preferences

23
END

24

You might also like