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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With