Saturday, August 24, 2013

View All Files in a Directory on Android

I was having a terrible time trying to figure out how to list all the files in a folder on Android. I know how to easily do it in C#, but java-Android is making life difficult. Finally I figured it out. The seemingly trivial was made difficult by vague exception messages.

The key is that the file you run listfile() on must be a directory. This was not clear from all the examples I found on other websites.

Log.d(TAG, "making the file f ");
File fileList = new File(context.getFilesDir(), filename);
fileList = fileList.getParentFile(); // get the directory, we must have a directory before calling listFiles()
String absPath = fileList.getAbsolutePath();
Log.d(TAG,"this is the file path "+absPath);
if (fileList != null){
Log.d(TAG, "getting all the files in the same directory ");
File[] filenames = fileList.listFiles();
if(filenames != null){
Log.d(TAG, "looping. ");
for (File tmpf : filenames){
//Do something with the files
Log.d(TAG, "FileName:" + tmpf.getName());
}
} else {
Log.d(TAG,"File names is null");
}
}
view raw gistfile1.java hosted with ❤ by GitHub

No comments:

Post a Comment