Reputation: 2862
I want to create a directory in external storage but I am unable to create it.
This is my code:
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path,"/appname/media/appimages/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
File file = new File(dir, "image" + ".jpg");
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(this,
new String[] { imagePath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
File file1 = new File(Environment.getExternalStorageDirectory().getPath() + "/MeaVita");
file1.mkdir();
// imageRoot.mkdirs();
Log.d("directory",dir.getAbsolutePath().toString());
I tried both using mkdirs() and mkdir(). But neither of them work. I am unable to see the folder at the path storage/emulated/0/ .
I am running this on android 23.0 onwards also I have added the permissions.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Does someone know what goes wrong in my code?
Thanks in advance.
Upvotes: 0
Views: 890
Reputation: 17813
I checked it .. Its a permission issue .. quick solution to switch to 22 instead of 23. or you need to handle permissions on runtime see : link
Upvotes: 0
Reputation: 1338
With certain permissions you need to check at runtime if the users accepts them you can do it by creating a method like this:
private void checkFilePermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasWriteExternalStoragePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
}
And then use it before you access your storage
Upvotes: 1