Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of requestCode in startActivityForResult

Tags:

android

I'm wondering if I am understanding the concepts of requestCode correectly. What is this integer for and does it matter what integer I set it to in:

private static int CAMERA_REQUEST = ???; 

Thank you

like image 249
user1178988 Avatar asked Feb 13 '12 21:02

user1178988


1 Answers

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.

like image 174
Bibek Shrestha Avatar answered Sep 22 '22 07:09

Bibek Shrestha