A very useful feature of desktop applications is being able to browse the contents of a folder programmatically, which makes all manner of explorer type applications possible. Appcelerator Titanium makes this very easy to do.

Thanks to to mrobinson on the Titanium for pointing out the needed function in the API. I wasted several hours looking in the wrong place for how to do this.

The functionality to get the directory listing is found in the File object.

The example listed in the Titanium API is as follows:

   var win = Titanium.UI.getCurrentWindow();

   win.openFolderChooserDialog(function(folderResponse) {
      var file = Titanium.Filesystem.getFile(folderResponse[0]);
      var listing = file.getDirectoryListing();
      for (var i = 0; i < listing.length; i++) {
         alert('Name: ' + listing[i].name() +
            ',isDirectory: ' + listing[i].isDirectory() +
            ',isHidden: ' + listing[i].isHidden());
      }
   });

First we show a Folder Chooser dialog, which works very similarly to the File Chooser dialog which I covered in a previous blog post. The file chooser calls a callback function and asses an array as the parameter. If a folder is selected, it will be contained in the first element in the array.

Next, we get a reference to the file Titanium.Filesystem.getFile()with the folder path as the parameter.

The crucial step then, is to call file.getDirectoryListing() which gets an array of file objects representing the files and folders in the selected folder.

You can then loop through this array and process the results in whichever way your application needs.

Some useful functions are listing[i].name() which lists the name of the file or folder without the full path, listing[i].isDirectory() which returns whether it is a folder or file, and listing[i].nativePath() which returns the full path of the file.

You can view the Titanium API Documentation for more details.

Share