Why can i not make a directory inside Environment.DIRECTORY_PICTURES?

社会主义新天地 提交于 2020-01-03 15:19:10

问题


This is my code

File selfieLocation = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
               "Daily Selfies");
boolean isDirectory = false;
if(!selfieLocation.isDirectory()) {
        //Creates directory named by this file
        selfieLocation.mkdir();
        isDirectory = selfieLocation.isDirectory();
 }
 //array of strings 
 for(String selfiePath: selfieLocation.list()) {
        selfies.add(selfiePath);
 }

Basically what I am trying to do is create my own customizable directory inside of the standard directory in which to place pictures that are available to the user.

I looked at related threads and saw this one, Android: unable to create a directory in default pictures folder. However I made sure that I had a call to getExternal...., and not just have Environment.DIRECTORY_PICTURES as a parameter. I also looked on here http://developer.android.com/guide/topics/data/data-storage.html#filesExternal and saw that I had the right method call/format to create a customizable folder in external memory. The docs example was

File file = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
    Log.e(LOG_TAG, "Directory not created");
}

I stepped through my code and saw that the local variable isDirectory stayed at false even after the call to selfieLocation.mkdir(). Does anyone know why this directory cannot be created?


回答1:


Try to create directory with File#mkdirs(), not File#mkdir(). The latter assumes that all parent directories are already in place, so it won't create directory if any of its parents don't exist.
Also, take a look at your permissions in AndroidManifest.xml. You need the following permissions in order to read/write the content on external storage:

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

android.permission.READ_EXTERNAL_STORAGE isn't required for now, but it will be in the future releases of Android.



来源:https://stackoverflow.com/questions/27165492/why-can-i-not-make-a-directory-inside-environment-directory-pictures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!