What is the meaning of requestCode in startActivityForResult

The requestCode helps you to identify from which Intent you came back. For example, imagine your Activity A (Main Activity) could call Activity B (Camera Request), Activity C (Audio Recording), Activity D (Select a Contact).

Whenever the subsequently called activities B, C or D finish and need to pass data back to A, now you need to identify in your onActivityResult from which Activity you are returning from and put your handling logic accordingly.



    public static final int CAMERA_REQUEST = 1;
    public static final int CONTACT_VIEW = 2;

    @Override
    public void onCreate(Bundle savedState)
    {
        super.onCreate(savedState);
        // For CameraRequest you would most likely do
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);

        // For ContactReqeuest you would most likely do
        Intent contactIntent = new Intent(ACTION_VIEW, Uri.parse("content://contacts/people/1"));
        startActivityForResult(contactIntent, CONTACT_VIEW);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == Activity.RESULT_CANCELED) {
            // code to handle cancelled state
        }
        else if (requestCode == CAMERA_REQUEST) {
            // code to handle data from CAMERA_REQUEST
        }
        else if (requestCode == CONTACT_VIEW) {
            // code to handle data from CONTACT_VIEW
        }
    }


I hope this clarifies the use of the parameter.


Look my example here. The integer you have to set can be any one positive. Only do not make them the same, you don't want to mix them, do you? And don't put them to 0 - it is returning without result, IMHO, I had strange behaviours with 0. As for negatives, don't use them, too, they are reserved for negative results in other callActivities functions.


Explanation is illustrated in picture.

 public void onActivityResult(int requestCode, int resultCode, Intent data)

app receives results from the different intents via above method only. So how will you understand which intent had replied to you? For that reason, before invoking the intents we put a self defined TAG/Label which is called requestCode. By our own defined requestCODE we can check which intent's result we have received.

Here in requestCode in the example I have given 1001 for Camera Intent. You can put any of your desired number. 1200 or 2001 or 21. Any Positive integers ranging to ~2^16.

See the picture attached.