Android mkdirs not working

I need to save a camera image on Android. I used write permission on external storage in the manifest and I use this code

File dir = new File(Environment.getExternalStorageDirectory(), "Test"); if (!dir.exists() || !dir.isDirectory()) dir.mkdirs(); String path = dir.getAbsolutePath(); Log.d(TAG, path); //log show the path File file = new File(dir.getAbsolutePath() + "/Pic.jpg"); Log.d(TAG, file.getAbsolutePath()); //again path is shown here outStream = new FileOutputStream(file); outStream.write(bytes); outStream.close(); Log.d(TAG, "onPictureTaken - wrote bytes: " + bytes.length); //fail here } catch (FileNotFoundException e) { Log.d(TAG, "not done"); //error is here (this exception is thrown) } catch (IOException e) { Log.d(TAG, "not"); } finally { } 

I also tried mkdir () instead of mkdirs () with the same result.

any idea what went wrong in the code?

thanks

+5
source share
6 answers

For those who are not as experienced as I am. I struggled with this problem, lost my hair for a while. I aimed at api 21 (to ensure compatibility) and it worked on candy, but on marshmallows this would not create a directory. I had permission to use in the manifest, but it still didn't work. Apparently, in Marshmallow, when you install it using the Android studio, he never asks you if you will allow him to allow, he just silently fails, as you have denied. You must enter Settings, applications, select your application and enable the permission switch.

+17
source

IDIOT ME! I used manifest permission, but when I installed the application on the phone, I did not issue storage permissions! ... I understand the negative answer to this question ... but I hope that if someone else comes across the same ... check your rights to the phone. Sorry for the inconvenience.

+2
source

if you are testing on android M, you should probably check Settings> Application> Permission to see if permission has been granted to access the repository. It saved me.

+1
source

You put

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

in AndroidManifest? If you are using android M, you should request user permission to write to sd, look here for an example

+1
source

You created a directory, not a file. Create a new file with the following code

 File file = new File(dir.getAbsolutePath() + "/Pic.jpg"); file.createNewFile() 
0
source

Try it. Grant runtime permission for marshmallows, it works fine in my application code:

  private String getFilename(String strFileName) { String filepath = Environment.getExternalStorageDirectory().getPath(); File fileBase = new File(filepath, "Test"); if (!fileBase.exists()) { fileBase.mkdirs(); } return (file.getAbsolutePath() + "/" + strFileName + file_exts[currentFormat]); } new File(getFilename(edt.getText().toString().trim())) 
0
source

Source: https://habr.com/ru/post/981325/


All Articles