Launching Activities and Handling Results

If you think back to Hour 3, "Building Android Applications," when we talked about application life cycle, you will recall that there are several ways to launch an activity. Specifically, there is a method called startActivityForResult() that allows you to launch an activity using an intent and then handle the result by implementing the calling activity class's onActivityResult() method.

The startActivityForResult() method takes two parameters: the intent to launch and a developer-defined request code. In this case, the calling activity is QuizSettingsActivity. You have two instances in which you want to start a new activity. The first instance is when the user clicks on the ImageButton control to start the camera capture activity. The second instance is when the user long-clicks on the ImageButton control to start the image gallery. Therefore, you need to define two request codes within QuizSettingsActivity:

static final int TAKE_AVATAR_CAMERA_REQUEST = 1; static final int TAKE_AVATAR_GALLERY_REQUEST = 2;

We will talk more about the startActivityForResult() method in a moment, but for now, let's focus on how the QuizSettingsActivity handles the results returned when the launched activity completes. You handle the result returned by the activity by implementing the onActivityResult() method of the QuizSettingsActivity class. Because you have more than one request code, you add a switch statement with two cases, one for camera results and one for image picker results:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case TAKE_AVATAR_CAMERA_REQUEST:

if (resultCode == Activity.RESULT_CANCELED) {

// Avatar camera mode was canceled. } else if (resultCode == Activity.RESULT_OK) { // TODO: HANDLE PHOTO TAKEN



if (resultCode == Activity.RESULT_CANCELED) {

// Avatar gallery request mode was canceled. } else if (resultCode == Activity.RESULT_OK) { // TODO: HANDLE IMAGE CHOSEN


Note that the user might launch an activity and then cancel it. In this case, the resultCode of the onActivityResult() method is Activity.RESULT_CANCELED. However, when the resultCode parameter is Activity.RESULT_OK, you should have a valid result to handle.

Because both cases result in a graphic you want to save as an application avatar, you can create a helper method called saveAvatar(). This method can take a bitmap, save it as a local file, and use it within the Been There, Done That! application. The pseudo-code for the saveAvatar() method looks like this:

private void saveAvatar(Bitmap avatar) {

// TODO: Save the Bitmap as a local file called avatar.jpg // TODO: Determine the Uri to the local avatar.jpg file // TODO: Save the Uri path as a String preference // TODO: Update the ImageButton with the new image

Was this article helpful?

0 0

Post a comment