1

I have an error in:

for (int i = 0; i <listfiles.length; i ++) {

I do not understand it because, if I already have all the permissions.

public static ArrayList<String> getFilePaths(String directory){
    ArrayList<String> pathArray = new ArrayList<>();
    File file = new File(directory);
    File[] listfiles = file.listFiles();
    for(int i = 0; i < listfiles.length; i++){
        if(listfiles[i].isFile()){
            pathArray.add(listfiles[i].getAbsolutePath());
        }
    }
    return pathArray;
}

Permission

enter image description here

Checking if the permits have been obtained.

enter image description here

enter image description here

Error: java.lang.NullPointerException: Attempt to get length of null array

3 Answers3

1

You need to request permission before any operation dynamically like below

if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
    // Permission is not granted
     if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
    }
}
PushpikaWan
  • 2,437
  • 3
  • 14
  • 23
0

From file.Java about the listFiles() method:

 * @return  An array of abstract pathnames denoting the files and
 *          directories in the directory denoted by this abstract pathname.
 *          The array will be empty if the directory is empty.  Returns
 *          {@code null} if this abstract pathname does not denote a
 *          directory, or if an I/O error occurs.
 *
 * @throws  SecurityException
 *          If a security manager exists and its {@link
 *          SecurityManager#checkRead(String)} method denies read access to
 *          the directory

Since you don't get a SecurityException and the list is null,
the only other options are:

  1. this abstract pathname does not denote a directory
  2. an I/O error occurs
forpas
  • 160,666
  • 10
  • 38
  • 76
0

You should review the javadoc for the listFiles() method.

https://developer.android.com/reference/java/io/File.html#listFiles()

null will be returned if the file is not a directory. To prevent the null pointer, you could check the file object first with isDirectory() and if false, don't execute the loop.

Greg Moens
  • 1,705
  • 8
  • 15