Search code examples
androidimage-galleryonactivityresult

how to get image from gallery


I'm trying to get image from the gallery of my device ... I'm having a dialog that has a button that initializes the gallery after the user chooses a photo the path of it should be returned ...

but the path is returned as null

that's how I do it -

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(
                        Intent.createChooser(intent, "Select Picture"),
                        SELECT_PICTURE);

In my onActivityResult -

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                photo_path = getPath(selectedImageUri);
                // photo_path=selectedImageUri.getPath();
                Globals.galleryFlag = true;
                DialogFragment pindiDialogFragment = new PinPhotoDialogFragment();
                pindiDialogFragment.show(getFragmentManager(), "pin photo");
                dismiss();
            }
        }
    }

And that's my getPath function -

    public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
            MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity.getContentResolver().query(uri,
            projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Solution

  • Call intent as below:

    Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
    

    Correct OnActivityResult as below:

     @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                ImageView imageView = (ImageView) findViewById(R.id.imgView);
                imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            }
        }
    

    Source: Android get image from gallery into ImageView