Reputation: 1220
I want to create a separate directory for images saved via my app. But I don't know where my code falls short. This is what I am doing to create a new directory in the root directory of external storage:
File root = Environment.getExternalStorageDirectory();
File directory = new File(root,"MYFOLDER");
if(!directory.exists()) {
directory.mkdirs();
}
I have already added the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission in my app manifest file. And I have tried this, this and this and others but nothing works.
Upvotes: 1
Views: 598
Reputation: 567
First give runtime storage permission by adding this lines, Because after android oreo you need to give runtime permission to access storage
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
then you can use this code
File apkStorage = new File(Environment.getExternalStorageDirectory() + "/" + "TestFolder");
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
Add requestLegacyExternalStorage="true" to application tag in manifest file
Upvotes: 1
Reputation: 1167
I use this which works:
private static final String IMAGE_DIRECTORY = "/mydirectory";
File Directory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!Directory.exists()) {
Directory.mkdirs();
}
Upvotes: 1