alka aswal
alka aswal

Reputation: 511

Why Environment.getExternalStoragePublicDirectory is not working in some devices(specially manufactured since early 2011)?

I am trying to store the images captured from camera to public storage directory, here is my part of code for storing image:

protected File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
                );
        return image;
    }

its working fine in most of the devices, but in some devices i get

java.io.IOException: open failed: ENOENT (No such file or directory)

So my question is why the same piece of code is working fine in most of the devices and why not in some devices and how to fix this issue?

Upvotes: 7

Views: 12528

Answers (3)

Milad Faridnia
Milad Faridnia

Reputation: 9477

you can use

File storageDir = new File(PATH_TO_PICTURES)

or

File storageDir =new File(PATH_TO_PICURES_EXTERNAL)

of course its better to check the directory first using this code:

if(storageDir.isDirectory())

Upvotes: 0

Aitor Viana
Aitor Viana

Reputation: 933

If you're storing your images in a public directory, I guess it is because you want to share those with other apps. You need to ask yourself the following question: "Do I want those files generated by my app to survive my app being uninstalled?" If the answer is no (which I recommend) you should use Context.getExternalMediaDirs() instead. Plus for API 19 and above, these directories do not need storage permissions!

If the answer is yes (O_o), you should use Environment.getExternalStorageDirectory() or Environment.getExternalStoragePublicDirectory(String). These always require storage permissions. Also, as you have already experienced and others pointed out, these directories might not yet exist. Check the API documentation for more info, but in short, you should call paths.mkdirs() before to ensure the dirs exist.

Upvotes: 1

Vytautas Berankis
Vytautas Berankis

Reputation: 325

Use context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) instead.

Upvotes: 3

Related Questions