Craig Archer
Craig Archer

Reputation: 43

NullPointerException: Attempt to get length of null array

I am developing an Android App. I have the below code to write a list of all files starting with XLR in a particular folder:

private List<File> getListFiles(File parentDir) {
    ArrayList<File> inFiles = new ArrayList<File>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        try {
            if ((file.exists()) && (file != null)) {
                if (file.isDirectory()) {
                    inFiles.addAll(getListFiles(file));
                } else {
                    if (file.getName().startsWith("XLR")) {
                        inFiles.add(file);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return inFiles;
}

On Android 10 and 11 it seems to be a problem. For Android 10 I have legacy storage enabled and Android 11 I have got access to all files. So the issue is not file access. The folder itself might not be in my app's folder, hence the need to be able to list out files

I know that there is an extensive page here on NPE's and I have tried my best to follow the advice there (I am checking that files exist and are not null), but still to no avail.

I feel that there's probably something so stupid, that a more experienced programmer would probably pick out in 2 seconds...

Upvotes: 1

Views: 6574

Answers (1)

Daniel Campos Olivares
Daniel Campos Olivares

Reputation: 2584

This problem would be easily solved just reading the documentation of the actual File package.

Documentation on the method File::listFiles:

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 null if this abstract pathname does not denote a directory, or if an I/O error occurs.

As you can see, that method can actually return null and not only an empty array, so you should check that the value isn't null before even trying to iterate over it.

Upvotes: 2

Related Questions