android – Why does MediaStore.Images.Media.insertImage always save images in the Pictures folder?-ThrowExceptions

Exception or error:

I would like to save my images in a folder that corresponds to the name of my app, instead of the default “Pictures” folder. Here’s my code in onRequestPermissionsResult:

if(requestCode == SAVE_IMAGE) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                try {
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + R.string.app_name + "/";
                    File dir = new File(path);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }

                    OutputStream out;
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

                    File photoFile = new File(path, timeStamp + ".jpg");
                    photoFile.createNewFile();

                    out = new FileOutputStream(photoFile);

                    Bitmap full_image_result = full_image.copy(full_image.getConfig(), true);
                    selectedFilter.apply(full_image_result);
                    full_image_result.compress(Bitmap.CompressFormat.JPEG, 90, out);

                    MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),photoFile.getAbsolutePath(), photoFile.getName(), photoFile.getName());

                    out.flush();
                    out.close();

                    Toast.makeText(getApplicationContext(),R.string.savedMessage, Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), R.string.noPermissions, Toast.LENGTH_LONG).show();
            }
        }
How to solve:

Somehow the path was wrong, replaced it with Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictura/" and now it’s working. I also replaced the insertImage call with

MediaScannerConnection.scanFile(this, new String[]{photoFile.getAbsolutePath()}, new String[]{"image/jpg"}, null);

, as CommonsWare suggested.

Leave a Reply

Your email address will not be published. Required fields are marked *