0

I'm trying to list all the files in a directory. Here is my code:

public List<String> MyFiles = new ArrayList<>();
dir = "/storage/sdcard0";
File f = new File(dir);

File[] files = f.listFiles();
for(File name: files) {
    MyFiles.add(name.getName());
}
Collections.sort(MyFiles);

The problem is that nearly all the files is repeated. For Instance I find .nomedia twice and sometimes thrice even thought there is only one file.

Edit:

I changed the code to sort the files correctly thanks to Vishwesh Jainkuniya, but still the same problem the files are repeated.

  • 1
    Possible duplicate of [How to list files in an android directory?](http://stackoverflow.com/questions/8646984/how-to-list-files-in-an-android-directory) – A_Arnold Aug 10 '16 at 19:14

1 Answers1

0

Problem-: sort function is not applicable for File[]

Solution:- create a string array and sort it.

Try this-:

First of all get the path of root dir

String path = Environment.getExternalStorageDirectory().toString();

Now append your dir name in path

path += "";

Now get the files in a array

File f = new File(path);        
File file[] = f.listFiles();
String[] fileName = new String[file.length];
for (int i=0; i < file.length; i++)
{
    fileName[i] = file[i].getName();
    Log.d("Files", "FileName:" + file[i].getName());
}

Now sort

Arrays.sort(fileName);

Vishwesh Jainkuniya
  • 2,821
  • 3
  • 18
  • 35
  • Oh, yeah sorry. I edited it but still the same, it's now sorted correctly but still the same problem. The problem lies in f.listFiles(); I checked the output and it repeats the names. – Khaled Emara Aug 11 '16 at 07:47