Search code examples
androidandroid-intentandroid-contentproviderandroid-galleryandroid-bitmap

Error While fetch image from gallary


I made code as below to get image:

private void openFileManager() {
    Intent i = new Intent(Intent.ACTION_PICK);
    i.setType("image/*");
    startActivityForResult(i, REQUEST_CODE_GALLERY);
}

And fetch image in onActivityResult method as below :

Uri uri = data.getData();
InputStream is = getContentResolver().openInputStream(uri);
Bitmap b = BitmapFactory.decodeStream(is);
iv1.setImageBitmap(b);

but get error as :

08-04 17:44:36.630 20795-20795/com.test E/image path: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Ffile%2F10750/ORIGINAL/NONE/1807946268
08-04 17:44:36.630 20795-20795/com.test E/image path: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Ffile%2F10750/ORIGINAL/NONE/1807946268
08-04 17:44:36.647 20795-20795/com.test W/System.err: java.io.FileNotFoundException: No such file or directory

Its pointing to the line : InputStream is = getContentResolver().openInputStream(uri);

I get this error in marshmallow, but not in Kitkat. I feel Google Photo App only return this type of URI in ActivityResult.

Edition : I get to know this is error when Internal Intent call Google Photo app for image selection. Tnx @Sanket. But how to fix this problem. Any code to handle URI from Google Photo and bifercate URI to get pic directly. Because I have to pass it in Glide Library function to render in ImageView.


Solution

  • try this code for image fetching in android 5,6

    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
            ParcelFileDescriptor parcelFileDescriptor =
                    getLocalContext().getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return image;
        }
    

    getLocalContext() is you local context.