Home Tags Archive
+ TWITTER Add to Google
Recent Articles

Android Activity startActivityForResult

Authors : luigi agosti - Date : 08/03/2011 - Views : 25426
android activity
I think we are all familiar with intents and startActivity() method. At least you are if you have done something with android. But we often do not consider the method startActivityForResult. Just to have an introduction this is what you can find out about startActivity on the online documentation:
Note: The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed.
Very often you need to know what was the result of an activity. Suppose you have a list of items and you can edit them in another activity, you may need to know the result of the edit. Was the item changed? or was the edit canceled? To do that we can use startActivityForResultActivity
It is really easy to use. You start and activity with a request code and you end it with a result code. The activity caller can then make use of the request code and the result code to implement a switcher and implement some logic. It is clear if you look at the following sample:
//so this are two calls with a different request code

startActivityForResult(intent, CREATE_REQUEST_CODE);

startActivityForResult(intent, EDIT_REQUEST_CODE);
In the same activity you need to implement the receiving method. It looks like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == CREATE_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {
Last part is in the activity being called. On the finish you have to specify the result code:
setResult(RESULT_CANCELED, null);


setResult(RESULT_OK, null);
To conclude I advise you to reuse the result codes already implemented in android sdk. In particular you can reuse at least
  • RESULT_CANCELED : Standard activity result : operation canceled.
  • RESULT_FIRST_USER : Start of user-defined activity results.
  • RESULT_OK : Standard activity result : operation succeeded.