Not able to set image to the imageView in android 12

2.4k views Asked by At

I am working on a camera application with camera 2 API. I am able to save the image to the picture directory and set it to the image view till android version 11 but on android 12, image is getting saved to the picture directory but not getting set to the image view I am getting an error as below-

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/1649228496340.jpg: open failed: ENOENT (No such file or directory)

My code for the functionality-

    String mImagePath;
    ImageView ivPhoto;

    if (!mImagePath.isEmpty()) {
        uri = Uri.fromFile(new File(mImagePath));
        Bitmap btmap = loadFromUri(uri);
        ivPhoto.setImageBitmap(btmap);
    }
    
    public Bitmap loadFromUri(Uri photoUri) {
    Bitmap image = null;
    try {
        // check version of Android on device
        if (Build.VERSION.SDK_INT > 27) {
            // on newer versions of Android, use the new decodeBitmap method
            ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), photoUri);
            image = ImageDecoder.decodeBitmap(source);
        } else {
            // support older versions of Android by using getBitmap
            image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}

I've also added requestLegacyExternalStorage="true" to the application tag in manifest to get it work for the APIs below Android 12. Stuck at this issue since yesterday, Please help.

1

There are 1 answers

7
Tungken On

In Android 12, your app must have MANAGE_EXTERNAL_STORAGE permission to access these additional files and directories using either the MediaStore API or direct file paths.

Please check the document here: https://developer.android.com/training/data-storage/manage-all-files