Android: unable to create directory in default photo folder

This is the code that I use to create a folder in the default image 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 the log I get:

 False False 

the first time the directory is missing, so False , but then I immediately create it using mkdirs() , so I expect the second log to be True , but even this is False and my application crashed due to a NullPointerException in the later part of the code

Please, help

thanks

+2
source share
2 answers

You are using Environment.DIRECTORY_PICTURES wrong way. It is just a String constant, like "Pictures" , but not a path. You need to get the path through Environment.getExternalStoragePublicDirectory(string)

 File pictureFolder = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES ); File imagesFolder = new File(pictureFolder, "images"); // etc 
+5
source

To generate a folder first, you need to add permission in AndroidMinifest.xml

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

Now call the following method to create a new folder in which the directories you want to create your own folder (this name must exist in the "Environment" list) and the name of your folder.

 File outputDirectory = GetPhotoDirectory(Environment.DIRECTORY_PICTURES, "YourFolder"); 

Create your folder using 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, you can use the code below

 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; } 

A call to create a file after creating a folder with a file directory. It will return your Uri file

 Uri fileUri = GenerateTimeStampPhotoFileUri(File outputDirectory); 
0
source

Source: https://habr.com/ru/post/1207786/


All Articles