Skip to content
Advertisement

TreeContentProvider just getting every Directory of my path. (File Filter)

im trying to get every folder of my path. Now Im getting just folders but as soon as some other file comes up it gives me a JavaNullPointerException. I know its beacuse of listFiles() but I dont know how to let it work otherwise. Can someone help me?

@Override
public Object[] getElements(Object inputElement) {
    return File.listRoots();
}

@Override
public Object getParent(Object element) {
    return ((File) element).getParentFile();
}

@Override
public boolean hasChildren(Object element) {
    Object[] obj = getChildren(element);       
    return obj == null ? false : obj.length > 0;
    
}

@Override
public Object[] getChildren(Object parentElement) {
    
    List<File> files = new ArrayList<>();
        for (File file : ((File) parentElement).listFiles()) {
            if (file.isDirectory()) {
                files.add(file);
            }
        }
    return ((File) parentElement).listFiles();
}

Advertisement

Answer

File.listFiles() returns null if the file is not a directory. This is causing your exception.

To just show directories use something like:

@Override
public Object[] getChildren(Object parentElement) {
   File parentFile = (File)parentElement;

   if (!parentFile.isDirectory()) {
      return new Object[0];
   }

   return parentFile.listFiles(File::isDirectory);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement