MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

22
MobAppDev SharedPreferences, Activity State Persistence, & Context Menus Vladimir Kulyukin Department of Computer Science Utah State University www.vkedco.blogspot.com

Transcript of MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

Page 1: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

MobAppDev

SharedPreferences, Activity State Persistence, &

Context Menus

Vladimir KulyukinDepartment of Computer Science

Utah State University

www.vkedco.blogspot.com

Page 2: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

Outline

● Shared Preferences● Shared Preferences & Inter-Activity Communication● Shared Preferences & Persistence of Activity States● Context Menus

Page 3: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

Shared Preferences &

Inter-Activity Communication

Page 4: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 5: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

Access to SharedPreferences Object

● Three common ways to get a SharedPreferences object for a given application:

Context.getSharedPreferences() Activity.getPreferences() PreferenceManager.getDefaultSharedPreferences()

Page 6: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

}

}

Page 7: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

SharedPreferences via PreferenceManager

// Use PreferenceManager and the application's context to initialize

// a SharedPreferences object inside a component

SharedPreferences mSharedPrefs =

PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Page 8: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 9: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

}

Page 10: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

}

Page 11: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

}

Page 12: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

When to Load Shared Preferences?

// onCreate() or onRestart()

@Override

public void onCreate(Bundle savedInstanceState) {

loadSharedPrefs();

buildGUI();

}

Page 13: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 14: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 15: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 16: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 17: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 18: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 19: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 20: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 21: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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

Page 22: MobAppDev (Fall 2014): Shared Preferences, Activity State Persistence, & Context Menus

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