Android Pick/Select Image from Gallery

Sometimes in your Android application you’ll want the user to choose an image from the gallery that’ll be displayed by the application (and even uploaded to your servers) after the selection is made. In this article we’ll see how to invoke a single interface from which the user is able to select images across all his apps (like Gallery, Photos, ES File Explorer, etc.) and folders (Google Drive, Recent, Downloads, etc.) using Intents.

Launch the Gallery Image Chooser

Triggering the following Intent from your Activity/Fragment, you can allow the user to select an image.

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
PICK_IMAGE_REQUEST is the request code defined as an instance variable.

Show Up the Selected Image in the Activity/Fragment

Now once the selection has been made, we’ll show up the image in the Activity/Fragment user interface, using an ImageView. For this, we’ll have to override onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Getting the Absolute File Path from Content URI

The Content URI returned can be different depending upon where the selection has been made from. Especially since Kitkat (API level 19) which introduces the Storage Access Framework (SAF) you get to see all your document storage providers while selecting a photo. The content URIs can different basis each provider and then if you try to use that to get the file path with a piece of code like this (used to generally work pre-Kitkat):
Uri uri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();
Log.d(TAG, DatabaseUtils.dumpCursorToString(cursor));
int columnIndex = cursor.getColumnIndex(projection[0]);
String picturePath = cursor.getString(columnIndex); // returns null
cursor.close();

Komentar