Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing a list of files in a ListView

I'm wondering how to show files from a directory in a ListView`. The files can be listed with:

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

and added to the ListView via ArrayAdapter but I don't get the usage of the ArrayAdapter.

like image 529
Alexander Fuchs Avatar asked Feb 16 '12 19:02

Alexander Fuchs


2 Answers

I guess you want to show the names of the files from that directory so you could try this:

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();
}

The adapter to use with the list :

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

For anything more complicated than showing the names of the files you have to implement a custom adapter.

like image 59
user Avatar answered Sep 22 '22 01:09

user


Or you can use something like this for a sorted String of filenames:

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

String[] listItems = fileDir.list();
Arrays.sort(listItems);
like image 45
user1813774 Avatar answered Sep 22 '22 01:09

user1813774