Why Environment.getExternalStoragePublicDirectory is not working in some devices(specially manufactured since early 2011)?
Solution 1
Use context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
instead.
Solution 2
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.
alka aswal
Updated on August 11, 2022Comments
-
alka aswal almost 2 years
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?
-
alka aswal about 9 yearsthank you @Vytautas .. bt if you can elaborate a little bit about why getExternalStoragePublicDirectory is not working in my case and why this will work, it will be great. :-)
-
Vytautas Berankis about 9 yearscalling 'getExternalStoragePublicDirectory' you are not sure that directory exists, so you must check it first if it does not egzists, create one. More information you can find here: link
-
alka aswal about 9 yearsok , that means, it is varying device to device , in some devices public directories exists and in some it doesn't exists, so that's why we have to check it first?
-
bhavya joshi almost 5 yearsi think it is deprecated now for newer versions
-
Vytautas Berankis almost 5 yearsNo, it is not. Tested on android P.
-
latifalbr about 4 yearsdeprecated in android Q
-
Vytautas Berankis about 4 yearsNo, its not (developer.android.com/reference/android/content/…). developer.android.com/reference/android/os/… and developer.android.com/reference/android/os/… are deprecated.