Reputation: 511
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
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
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
Reputation: 325
Use context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
instead.
Upvotes: 3