I implemented a quick button to look up an image using the installed Android Gallery app:
public void btnPickImage(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
And then, to get the Uri of the image selected by the user:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_IMAGE:
if ( resultCode == Activity.RESULT_OK ) {
Uri image = data.getData();
// Do something with the image now...
}
break;
}
}
The code opens the gallery and allows for selection of an image. Once selected, the gallery Activity closes and returns to my Activity.
But, onActivityResult was not getting called!!!
Now, if the Gallery was one of my own Activities, then I’d guess I was neglecting to call setResult() and finish() correctly.
Or that I was using startActivity() instead of startActivityForResult().
The problem, it turns out is that my requestCode was defined as:
private static final int REQUEST_IMAGE = -69; // Does not work!!!
And Android interprets the negative value requestCode as a plain old startActivity() instead of startActivityForResult().
The moral of the story is that we should always use positive values for requestCodes…
private static final int REQUEST_IMAGE = 69; // Works just fine!!!