This is the code i am using to create a folder in the default pictures folder:
File imagesFolder = new File(Environment.DIRECTORY_PICTURES, "/images");
if (!imagesFolder.exists()) {
Log.d("if imagesFolder exists - 1", "False");
imagesFolder.mkdirs();
} else {
Log.d("if imagesFolder exists - 1", "True");
}
if (!imagesFolder.exists()) {
Log.d("if imagesFolder exists - 2", "False");
imagesFolder.mkdirs();
} else {
Log.d("if imagesFolder exists - 2", "True");
}
in log i am getting:
False
False
for the 1st time the directory is not present, hence False
but then immediately i am creating it using mkdirs()
, hence i expect the 2nd log to be True
but even that is False
and my application crashed because of NullPointerException
in the later part of the code
Please help
Thank You
You are using Environment.DIRECTORY_PICTURES
the wrong way. It's just a String
constant like "Pictures"
but not a path. You need to get the path via Environment.getExternalStoragePublicDirectory(string)
File pictureFolder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
File imagesFolder = new File(pictureFolder, "images");
// etc
To generate a folder at first you need to add permission at AndroidMinifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Now call following method to create a new folder with in which Directory you want to create your folder(this name should exist in Environment. list) and your folder name.
File outputDirectory = GetPhotoDirectory(Environment.DIRECTORY_PICTURES, "YourFolder");
Generate your folder by this method
public static File GetDirectory(String inWhichFolder, String yourFolderName ) {
File outputDirectory = null;
String externalStorageState = Environment.getExternalStorageState();
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(inWhichFolder);
outputDirectory = new File(pictureDirectory, yourFolderName);
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
Log.e(LogHelper.LogTag, "Failed to create directory: " + outputDirectory.getAbsolutePath());
outputDirectory = null;
}
}
}
return outputDirectory;
}
If you want to create a file under your newly created folder then you can use below code
public static Uri GenerateTimeStampPhotoFileUri(File outputDirectory, String fileName){
Uri photoFileUri = null;
if(outputDirectory!=null) {
File photoFile = new File(outputDirectory, fileName);
photoFileUri = Uri.fromFile(photoFile);
}
return photoFileUri;
}
Call to create a file after creating the folder with File Directory. It will return your file Uri
Uri fileUri = GenerateTimeStampPhotoFileUri(outputDirectory, fileName);
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