Pages

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

Activity1.java:
final static int REQUEST_CODE = 1234;

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

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

Activity2.java:
...
  setResult(1);
  finish();
...

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:

Activity1.java:

...
@Override
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.

0 comments:

Post a Comment