3

I have a search button in MainActivity which launches SearchActivity. In SearchActivity, the user can either choose from one of the predefined categories listed, or can enter in a search query. The SearchActivity will return a different extra depending on which way the user searches. The code that runs in MainActivity will depend on which extra is returned.

I'm debating which way is better or more "correct". I've coded it both ways, and it works either way.

The first way I coded it was to check for the existence of the intent extra:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GET_SEARCH_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            if (data.getExtras().containsKey("extra1")) {
                extra1 = data.getStringExtra("extra1");
            }
            if (data.getExtras().containsKey("extra2")) {
                extra2 = data.getStringExtra("extra2");
            }
        }
        // plus rest of code for checking for RESULT_CANCELED
    }
}

The other way I coded it is by using custom result codes. The result codes RESULT_OK_CATEGORY and RESULT_OK_SEARCH are public static variables in MainActivity so that they can be accessed from SearchActivity, and sent back as a result code through setResult(MainActivity.RESULT_OK_CATEGORY, intent) or setResult(MainActivity.RESULT_OK_SEARCH, intent) respectively.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GET_SEARCH_REQUEST_CODE) {
        if (resultCode == RESULT_OK_CATEGORY) {
            extra1 = data.getStringExtra("extra1");
        } else if (resultCode == RESULT_OK_SEARCH) {
            extra2 = data.getStringExtra("extra2");
        }
        // plus rest of code for checking for RESULT_CANCELED
    }
}

Which way is better, and why? Checking for the existence of the extra, or checking for a custom result code?

mannykary
  • 812
  • 2
  • 10
  • 18
  • What does andriod doc says ? – Ajay Takur Jan 16 '15 at 20:14
  • I can't really find anything in the docs about custom result codes, but I don't see why they can't be used. Perhaps if there's a possibility that getting the extra could return null. – mannykary Jan 16 '15 at 20:18
  • http://stackoverflow.com/questions/2859831/startactivityforresult-and-intents-extras-it-seems-extras-are-not-pushed-back?rq=1 – Ajay Takur Jan 16 '15 at 20:54

1 Answers1

3

You should use resultCode because it's completely under your control. You may lose values set in Intent's extras, as revealed in this question (referenced by Ajay in the comments).

Note, if you use many custom result codes, it has been recommended to use a switch statement for code clarity.

Community
  • 1
  • 1
gknicker
  • 5,509
  • 2
  • 25
  • 41