我使用下面的代码 从SD卡中获取文件夹 以及删除空文件夹
File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
// delete empty folder
if (inFile.listFiles().length == 0) {
inFile.delete();
}
// add names into an ArrayList and populate ListView.
listingSDCard.add(inFile.getName());
}
}
但我不知道 如何刷新listview ,因为我注意到空文件夹已经从SD卡以编程方式删除,但仍然可以看到列表,我是使用简单列表,我知道 notifyDataSetChanged()帮助我们刷新列表。
我的 完整代码:
final ListView listView = (ListView) findViewById(R.id.listViewAnimals);
List<String> listingSDCard = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().toString()+"/Church Application/";
File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
// delete empty folder
if (inFile.listFiles().length == 0) {
inFile.delete();
}
// add names into an ArrayList and populate ListView.
listingSDCard.add(inFile.getName());
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.activity_archive_list,
listingSDCard);
listView.setAdapter(arrayAdapter);
已编辑的代码: -
final ListView listView = (ListView) findViewById(R.id.listViewAnimals);
List<String> listingSDCard = new ArrayList<String>();
String path = Environment.getExternalStorageDirectory().toString()+"/Church Application";
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.activity_archive_list,
listingSDCard);
File f = new File(path);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
// delete empty folder
if (inFile.listFiles().length == 0) {
inFile.delete();
arrayAdapter.notifyDataSetChanged();
}
// add names into an ArrayList and populate ListView.
listingSDCard.add(inFile.getName());
}
}
listView.setAdapter(arrayAdapter);
问题仍未解决 - 仍然将空文件夹名称导入ListView,而SD卡中不存在文件夹!
答案 0 :(得分:2)
试试这个:
for (File inFile : files) {
if (inFile.isDirectory()) {
// delete empty folder
if (inFile.listFiles().length == 0) {
inFile.delete();
} else {
// add names into an ArrayList and populate ListView.
listingSDCard.add(inFile.getName());
}
}
}
虽然您要删除系统中的文件夹,但是要将其添加到listingSDCard
,您需要将其添加到其他文件夹中。
答案 1 :(得分:0)
在适配器上拨打notifyDataSetChanged()。
代码:
arrayAdapter.notifyDataSetChanged();
你也可以使用它:
arrayAdapter.invalidateViews();
答案 2 :(得分:0)
arrayAdapter.notifyDataSetChanged();
删除文件夹后添加此行。