List files from a specific folder

Asked

Viewed 351 times

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()) returns me the following error:

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

I already added the permissions!

How do I list files from a folder?

  • Granted permission ~Runtime read or only in Manifest??

  • What value is in your PATH variable?

  • I added the PATH there!

1 answer

2


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

You can create a static method, for example permissReadFile() passing by its context. 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 in any part of your project so:

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

See more details in the documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.