Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android mkdirs not working

Tags:

android

mkdirs

i need to save an image from camera on android. i used the write external storage permission in manifest and i am using 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() same result.

any idea what went wrong in the code?

thanks

like image 240
lallous34 Avatar asked Oct 17 '16 13:10

lallous34


2 Answers

For those not as experienced like me. I fought this issue, lost hair for some time. I am targeting api 21 (for compatibility sake) and it worked on lollipop but on marshmallow it would not create the directory. I did have the "uses" permission in the manifest but it still would not work. Apparently in Marshmallow when you install with Android studio it never asks you if you should give it permission it just quietly fails, like you denied it. You must go into Settings, apps, select your application and flip the permission switch on.

like image 72
protocolkey Avatar answered Sep 28 '22 06:09

protocolkey


Some one like me who was trying in Android10. Please use below API in manifest:

<application android:requestLegacyExternalStorage="true" ... >     ...   </application>  

Latest Update From Google: After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.

like image 21
NanPd Avatar answered Sep 28 '22 04:09

NanPd