Well this certainly was harder than it should have been! The first three steps are pretty straight forward.
Set up an ID for the activity result.
1.
private
final
int
ACTIVITY_CHOOSE_PHOTO =
1
;
Mission complete! On with the next phase. Now we need something to trigger the "chooser" activity.
1.
Intent chooseFile =
new
Intent(Intent.ACTION_GET_CONTENT);
2.
chooseFile.setType(
"image/*"
);
3.
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
4.
5.
startActivityForResult(Intent.createChooser(chooseFile,
"Choose a photo"
), ACTIVITY_CHOOSE_PHOTO);
Simple enough. Of course, if we're expecting a result then we need to actually do something with it.
So in your Activity.onActivityResult() callback method:
01.
@Override
02.
protected
void
onActivityResult(
int
requestCode,
int
resultCode, Intent data) {
03.
switch
(requestCode) {
04.
case
ACTIVITY_CHOOSE_PHOTO: {
05.
if
(resultCode == RESULT_OK) {
06.
String filename = parseUriToFilename(data.getData());
07.
08.
if
(filename !=
null
) {
09.
moustachify(filename,
null
);
10.
}
11.
}
12.
break
;
13.
}
14.
}
15.
}
OK, the first three steps are done. It's just copy pasting code anyway...
Now the magic calculations come into play to get the filename. Otherwise you'll get references to the media manager and other funky stuff we don't really care about.
Note: This is the exact same code you'll see in the post Android: Add your application to the "Share" menu as they use information from the same activities.
01.
public
String parseUriToFilename(Uri uri) {
02.
String selectedImagePath =
null
;
03.
String filemanagerPath = uri.getPath();
04.
05.
String[] projection = { MediaStore.Images.Media.DATA };
06.
Cursor cursor = managedQuery(uri, projection,
null
,
null
,
null
);
07.
08.
if
(cursor !=
null
) {
09.
// Here you will get a null pointer if cursor is null
10.
// This can be if you used OI file manager for picking the media
11.
int
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
12.
cursor.moveToFirst();
13.
selectedImagePath = cursor.getString(column_index);
14.
}
15.
16.
if
(selectedImagePath !=
null
) {
17.
return
selectedImagePath;
18.
}
19.
else
if
(filemanagerPath !=
null
) {
20.
return
filemanagerPath;
21.
}
22.
return
null
;
23.
}
Now that you've solved this problem, I'm sure there's another waiting for you under the lid somewhere in the near future...