Sunday, 3 May 2015

Correctly implementing OnActivityResult for Android

When the an activity launch another activity and it want to know the result of such activity, the best way to do it is using startActivityForResult and then, override the method onActivityResult to handle the result.

onActivityResult has tree parameters:

  • requestCode: integer. It is the number used to launch the activity. It must be unique inside an activity.
  • resultCode: integer. The result returned by the launched activity. By default the class Activity comes with RESULT_OK, and RESULT_CANCELED. The launched activity could specify any another integer for the result.
  • data: intent. It is optional. It could be empty if the launched activity has not specify any data.
By using the inherence property of Object oriented language that Java is, more and more an activity is inherited by another activity. In this case, both parent and son could override the method onActivityResult. So, there is a chance they share the same requestCode and even handle the same result code.

For this case, here is what I consider correct implementation of onActivityResult:


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case (REQUEST_CODE_MY_RESULT_ACTIVITY_ID):
                switch (resultCode) {
                    case (RESULT_OK):
                        // Result is ok for the activity.
                        // Do things in accordance
                        break;
                    case (RESULT_CANCELED):
                        // Result has been canceled (the activity could be finished without
                        // passing correctly the data
                        break;
                    case (MyResultActivity.OTHER_POSSIBLE_RESULT):
                        // The activity could set special results that should be public static final
                        // Handle it here
                        break;
                    default:
                        super.onActivityResult(requestCode, resultCode, data);
                        break;
                }
            case (REQUEST_CODE_MY_ANOTHER_ACTIVITY_ID):
                switch (resultCode) {
                    // Here goes the cases for the another activity id
                    default:
                        super.onActivityResult(requestCode, resultCode, data);
                        break;
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

The special thing that it has is by each switch, it implements the default case when it called the onActivityResult of its parent. This is the same way as say if a certain case cannot be managed by the son, ask its parent to manage it.

More information

No comments:

Post a Comment