List files from a specific folder

2

I have the following code:

public static final String PATH ="/Conceitos";
    public  static List<String> loadFilesName() throws IOException{
        List<String> strings = new ArrayList<>(0);
        File root = android.os.Environment.getExternalStorageDirectory();
        File dir = new File(root.getAbsolutePath()+PATH);
        if(!dir.exists()){
            dir.mkdirs();
            return strings;
        }
        if(dir.isDirectory()){
            for(final File f :  dir.listFiles()){
                strings.add(f.getName());
            }
        }
        return strings;
    }

The folder is already created, and has a file, but when I try to access the list ( dir.listFiles() ) I get the following error:

  

W / System.err: java.lang.NullPointerException: Attempt to get length of   null array

I've already added the permissions!

How do I list the files in a folder?

    
asked by anonymous 30.03.2017 / 20:14

1 answer

2

In addition to granting permission on AndroidManifest.xml , from Android 6.0 (API level 23), users grant permissions to applications while they are running, not when they are installed.

You can create a static method, such as permissReadFile() , passing its context parameter. See below:

public static final int CHECK_PERMISSION_REQUEST_READ_FILES = 61;
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean permissReadFile(Activity activity){
    boolean res = true;
    if (activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        if (activity.shouldShowRequestPermissionRationale(
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
        }

        activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                CHECK_PERMISSION_REQUEST_READ_FILES);
        res = false;
    }
    return res;
}

And use it anywhere in your project like this:

if (CheckPermission.permissReadFile(this)) {
     // se entrar aqui é porque já concedeu permissão de leitura
}

See details in the documentation .

    
30.03.2017 / 20:56