Wednesday, 15 June 2011

First Steps: Returning values from an Activity

How do I return  a value from an Activity?
Below is some simple example code for creating a new Intent to launch an Activity named Activity1. Here we use the startActivityForResult method which takes the intent and an identifier (an arbitrary integer):
final static int REQUEST_CODE = 1234;

private void startActivity() {
  Intent myIntent = new Intent(getBaseContext(), Activity2.class);
  startActivityForResult(myIntent, REQUEST_CODE);

In your second activity you should use the following code to return a result value and terminate the activity:

Returning to your first activity and override the activity's onActivityResult method as below. Check the result code to determine the result is coming from the expected source then you can read resultCode and change logic depending upon its value:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(requestCode == REQUEST_CODE) {
    // Do something with resultCode

It is worth noting that you can not open activities (or dialogs for that matter) in a modal fashion, in fact nothing is modal in android as that would lock the UI which is not permitted. Listeners are always used to receive the results.


Post a Comment