Display a list of files in a ListView

I am wondering how to show files from a directory in ListView`. Files can be listed with:

File dir = new File(dirPath);
File[] filelist = dir.listFiles();

and added in ListViewthrough ArrayAdapter, but I do not use ArrayAdapter.

+5
source share
2 answers

I think you want to show the file names from this directory so that you can try the following:

File dir = new File(dirPath);
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
   theNamesOfFiles[i] = filelist[i].getName();
}

Adapter for use with list:

new ArrayAdapter<String>(this, android.R.layout.simple_list_item, theNamesOfFiles);

For something more complex than displaying file names, you must implement a custom adapter.

+14
source

Or you can use something like this to sort Stringfrom filenames:

File dataDirectory = Environment.getDataDirectory();
File fileDir = new File(dataDirectory, "data/com.yourapp.app/files");

String[] listItems = fileDir.list();
Arrays.sort(listItems);
+1
source

All Articles