Reputation: 17119
I'm trying to list all folders in sdcard via ListAdapter. But I'm getting runtime exceptions @ item.add(file.getName() + "/");
. Is there a better way to convert File[]
to List<String>
?
private List <String> item = null;
String extState = Environment.getExternalStorageState();
if (!extState.equals(Environment.MEDIA_MOUNTED)) {
....
} else {
File sd = Environment.getExternalStorageDirectory();
FileFilter filterDirectoriesOnly = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] sdDirectories = sd.listFiles(filterDirectoriesOnly);
for (int i = 0; i < sdDirectories.length; i++) {
File file = sdDirectories[i];
item.add(file.getName() + "/");
}
ArrayAdapter <String> fileList = new ArrayAdapter <String>(this, R.layout.row, item);
setListAdapter(fileList);
}
Upvotes: 0
Views: 6466
Reputation: 54242
You can make it a little shorter by using an enhanced for loop:
File[] sdDirectories = sd.listFiles(filterDirectoriesOnly);
for (File file : sdDirectories)
{
item.add(file.getName() + "/");
}
There's a method to get file names directly, but they won't have your trailing /
, and you have to be able to filter by file name:
String[] fileNames = sd.list(fileNameFilter);
List<String> fileNamesList = Arrays.asList(fileNames);
Upvotes: 1
Reputation: 13501
You are getting runtime Exception bacause
private List item = null;
is never initialised..
so first initialise then add..
What ever you are doing seems just right.. except that initialization..
Upvotes: 1
Reputation: 7302
Initialize your list (hence the Exception). But apart from that, looks pretty much alright to me. I mean, it is atleast what I would do. The only thing I would recommend here is that you don't re-instantiate the variables File sd
and FileFilter filterdirectoriesOnly
within the function, because I assume you would be calling it again and again as the user clicks on a directory and then loads results for a new directory. So the two objects I mentioned are the same but being re-initialised every time you make a call. You could just move it outside.
Upvotes: 0