Scott Chambers
Scott Chambers

Reputation: 611

Duplicate Array Listing

Ive been working on a simple directory scan that shows text files, than then prints the output in to a text area. How ever for somereason it will duplicate the output if i try to use it again below is the public array:

public ArrayList<File> getfile(File dir) {
        File listFile[] = dir.listFiles();
        if (listFile != null && listFile.length > 0) {
            for (int i = 0; i < listFile.length; i++) {

                if (listFile[i].isDirectory()) {
                    fileList.add(listFile[i]);
                    getfile(listFile[i]);

                } else {
                    if (listFile[i].getName().endsWith(".txt")) {
                        fileList.add(listFile[i]);
                    }
                }

            }
        }
        return fileList;
    }

Here is the onclick button code

File root = new File(Environment.getExternalStorageDirectory() + File.separator + user_inputfilename); //"searches what the userinput"
                            getfile(root);
                            for (int i = 0; i < fileList.size(); i++) {
                                newText.append(fileList.get(i).getName()+"\n");
                            }

I really dont know what ive done wrong? Is there a way to clear the array? anyhelp would be greatly appreciated. Thank you

Upvotes: 0

Views: 42

Answers (1)

Jonathan Sterling
Jonathan Sterling

Reputation: 604

You appear to be looking recursively in subdirectories too? In any case, try this. Where you were calling getFiles(dir) do fileList = getTextFilesRecursively(dir) instead:

  public ArrayList<File> getTextFilesRecursively(File dir) {
    return getTextFilesRecursively(dir, new ArrayList<>());
  }

  private ArrayList<File> getTextFilesRecursively(File dir, ArrayList<File> textFiles) {
    File[] allFilesAndFoldersInDir = dir.listFiles();

    if(textFiles == null) {
      textFiles = new ArrayList<>();
    }

    if (allFilesAndFoldersInDir != null && allFilesAndFoldersInDir.length > 0) {
      for (File fileOrFolderInDir : allFilesAndFoldersInDir) {
        if (fileOrFolderInDir.isDirectory()) {
          getTextFilesRecursively(fileOrFolderInDir, textFiles);
        } else if (fileOrFolderInDir.getName().endsWith(".txt")) {
          textFiles.add(fileOrFolderInDir);
        }
      }
    }

    return textFiles;
  }

I believe your underlying issue was fileList.add(listFile[i]); because fileList was scoped outside of the method and was being reused and appended to. Now we use textFiles instead, which should be empty each time the method is first called. A simpler fix would be to do fileList = new ArrayList<>() immediately before you call getFiles(dir);, however the code above is far better.

Upvotes: 1

Related Questions