mobappdev (fall 2014): shared preferences, activity state persistence, & context menus
Post on 22-Jun-2015
191 Views
Preview:
TRANSCRIPT
MobAppDev
SharedPreferences, Activity State Persistence, &
Context Menus
Vladimir KulyukinDepartment of Computer Science
Utah State University
www.vkedco.blogspot.com
Outline
● Shared Preferences● Shared Preferences & Inter-Activity Communication● Shared Preferences & Persistence of Activity States● Context Menus
Shared Preferences &
Inter-Activity Communication
Shared Preferences● SharedPreferences class provides a framework for
saving and retrieving key/value pairs of primitive data● Shared preferences used for saving user's lightweight
application preferences, UI states, application settings● Shared preferences can also be used for inter-activity
communication● The saved data persist across user sessions even
when the application is terminated
Access to SharedPreferences Object
● Three common ways to get a SharedPreferences object for a given application:
Context.getSharedPreferences() Activity.getPreferences() PreferenceManager.getDefaultSharedPreferences()
Getting Shared Preferences
public class MyAct extends Activity {
// The activity is created
public void onCreate(Bundle savedInstanceState) {
static final String PREFS_FILE = “MySharedPrefs”;
// some code
SharedPreferences sprefs = getSharedPreferences(PREFS_FILE,
MODE_PRIVATE);
int my value = sprefs.getInt(“my key”, -1);
}
}
SharedPreferences via PreferenceManager
// Use PreferenceManager and the application's context to initialize
// a SharedPreferences object inside a component
SharedPreferences mSharedPrefs =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Which Access Method to Use?
● Contex.getSharedPreferences() should be used if you have to identify multiple preferences files by name
● Activity.getPreferences() should be used when you have only one preference file for your activity
● PreferenceManager.getDefaultSharedPreferences() should be used when multiple components within the same application share the same default preference file
Persisting Shared Preferences
// grab the strings entered by the user, put them into the SharedPreferences
// Editor under appropirate keys and persist them via commit().
private void saveSharedPrefs() {
SharedPreferences.Editor spEditor = mSharedPreferences.edit();
spEditor.putInt(“my key”, 10);
spEditor.commit();
}
When to Persist Shared Preferences?
// onPause() is a sensible place to persist shared preferences
@Override
protected void onPause() {
super.onPause();
Log.d(LOGTAG, "onPause()");
saveSharedPrefs();
}
Loading Shared Preferences
// You have to know the key to load its persisted shared preference value.
private void loadSharedPrefs() {
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int persisted_val = mSharedPrefs.getInt(“my key”, 0);
}
When to Load Shared Preferences?
// onCreate() or onRestart()
@Override
public void onCreate(Bundle savedInstanceState) {
loadSharedPrefs();
buildGUI();
}
Review: Activity's Lifecycle
● An actvity's lifecycle is a set of states● When the current state of an activity changes, the Android OS
notifies the activity of that change● The Android developer manages the activity's lifecycle by
implementing the standard callback methods that are called on the activity object when its state changes (e.g., activity is created, stopped, resumed, and destroyed)
● Callback implementation is the only leverage the developer has over activities
Managing Activity State
● When an Activity is stopped or paused, its state is preserved● When an Activity is destroyed by the system, the next time
Activity starts, it must be re-created● The problem is that the user/developer is often unaware the
the activity has been destroyed and must be recreated, which results in unpleasant surprises and crashes
onSaveInstanceState()● The Android documentation states that “the system calls
onSaveInstanceState() before making the activity vulnerable to destruction”
● The method onSaveInstanceState() receives a Bundle where the developer can place key/value pairs using methods putInt(), putString(), etc.
● If the system kills the application, the saved Bundle is passed to both onCreate() and onRestoreInstanceState()
Retriving Data from Saved Bundles
● Saved key/value pairs can be extracted from saved Bundles in onCreate() or onRestoreInstanceState()
● If nothing was saved, the passed Bundle is null● There appears to be no guarantee that onSaveInstanceState() will
be called● The big deal also is that there appears to be no guarantee that
onRestoreInstaceState() will be called
Android Documentation Note
This is a direct quote on onSaveInstanceState() documentation:
“If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().”
Source: http://developer.android.com/guide/components/activities.html#Lifecycle
Problem
Implement an application, PictureBrowser with two activities, PictureBrowserAct and PictureProcessAct. PictureBrowserAct allows the user to browse up and down through a collection of images and grayscale each image via a ContextMenu. PictureProcessorAct displays the grayscale image. The two activities communicate via shared preferences.
source code is here
The source code repo does not contain the images; images are in this older repo
Main Activity● A screenshot of the main activity is shown
on the left● The two arrows below are actually two
buttons with image backgrounds● The images are not included in the git
repo (replace them with your own)● The buttons allow you to navigate up and
down an array images● A ContextMenu is associated with the
ImageView above the buttons
Main Activity● PictureBrowserAct.java is the main activity of this application● This activity furnishes you an example of how to save and load
shared preferences: see methods saveSharedPrefs() and loadSharedPrefs()
● loadSharedPrefs() is called in onCreate(): if you comment it out and run the application, you will notice that the image selected on the previous run is not displayed: in other words, the application always starts with the first image and does not load the saved preferences
● saveSharedPrefs() is called in onStop()
ContextMenu● ContextMenu is registered with the ImageView
member PictureBrowserAct.java called mPicture
● The registration is done via the call this.registerForContextMenu(mPicture) in onCreate()
● The actual implementation of ContextMenu is done by overriding two methods in PictureBrowserAct.java: onCreateContextMenu() and onContextItemSelected()
● ContextMenus are invoked by long clicks
Comments on Source Code● A click on Tsaritsino Wikipedia displays the
Tsaritsyno wiki page in English
● A click on Царицыно Википедия displays the Tsaritsyno wiki page in Russian
● A click on Grayscale Image takes the current image, saves its number id in a shared preferences file and invokes PictureProcessorAct.java
● PictureProcessorAct.java, when it starts, reads the number of the saved image id from the shared preferences file, grayscales it, and displays it in an ImageView, as shown on the left
top related