Android: Select and open an image from Android's image gallery

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.

private final int ACTIVITY_CHOOSE_PHOTO = 1;

Mission complete! On with the next phase. Now we need something to trigger the "chooser" activity.

Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("image/*");
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);

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:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case ACTIVITY_CHOOSE_PHOTO: {
if (resultCode == RESULT_OK) {
String filename = parseUriToFilename(data.getData());

if (filename != null) {
moustachify(filename, null);
}
}
break;
}
}
}

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.

public String parseUriToFilename(Uri uri) {
String selectedImagePath = null;
String filemanagerPath = uri.getPath();

String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);

if (cursor != null) {
// Here you will get a null pointer if cursor is null
// This can be if you used OI file manager for picking the media
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
selectedImagePath = cursor.getString(column_index);
}

if (selectedImagePath != null) {
return selectedImagePath;
}
else if (filemanagerPath != null) {
return filemanagerPath;
}
return null;
}

Now that you've solved this problem, I'm sure there's another waiting for you under the lid somewhere in the near future...

1vcZA

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog