Starting an activity for a result

Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling startActivityForResult() (instead of startActivity()). To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.

For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here’s how you can create such an intent and handle the result:

private void pickContact() {

// Create an intent to "pick" a contact, as defined by the content provider URI

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);

startActivityForResult(intent, PICK_CONTACT_REQUEST);

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// If the request went well (OK) and the request was PICK_CONTACT_REQUEST

if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {

// Perform a query to the contact's content provider for the contact's name

Cursor cursor = getContentResolver().query(data.getData(),new String[] {Contacts.DISPLAY_NAME}, null, null, null);

if (cursor.moveToFirst()) { // True if the cursor is not empty

int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);

String name = cursor.getString(columnIndex);

//         Do something with the selected contact's name...

}

}

}

 

This example shows the basic logic you should use in your onActivityResult() method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then the resultCodewill be RESULT_OK—and whether the request to which this result is responding is known—in this case, therequestCode matches the second parameter sent with startActivityForResult(). From there, the code handles the activity result by querying the data returned in an Intent (the data parameter).

What happens is, a ContentResolver performs a query against a content provider, which returns a Cursorthat allows the queried data to be read. For more information, see the Content Providers document.

For more information about using intents, see the Intents and Intent Filters document.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s