【发布时间】:2014-03-25 23:04:32
【问题描述】:
我已经在 stackoverflow 上看过这些问题:
http://stackoverflow.com/questions/22332957/display-media-files-in-listview-nullpointerexception
http://stackoverflow.com/questions/9317483/showing-a-list-of-files-in-a-listview
http://stackoverflow.com/questions/5800981/how-to-display-files-on-the-sd-card-in-a-listview
http://stackoverflow.com/questions/9782168/how-to-show-audio-files-in-a-listview-in-android
但它们都不适用于我的代码。我不知道为什么它不起作用?
我想要做的是创建一个列表视图来显示特定文件夹中的所有文件。我想要显示的特定文件夹是下载文件夹(如果您将手机插入 USB,您可以看到该文件夹)。澄清一下,在我的电脑上,目录如下所示:
This PC\Nexus 4\Internal storage\Download
这是我的代码(在我的 onCreate 方法中):
arraylist = new ArrayList<String>();
listview = (ListView) findViewById(R.id.list);
File file = new File(Environment.DIRECTORY_DOWNLOADS);
File[] list = file.listFiles();
if (list.length == 0)
{
Log.w("oh no", "oh no");
}
else {
for( int i=0; i < list.length; i++)
{
arraylist.add( list[i].getName() );
}
}
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1
,arraylist);
listview.setAdapter(adapter);
我试过了
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
我也试过
File directory = Environment.getExternalStorageDirectory();
file = new File(directory+ "/Download");// + "/Test");
虽然还是不行。
我的日志猫说从声明 for 循环的行开始有一个 nullpointerexception:
for( int i=0; i < list.length; i++)
非常感谢您!
【问题讨论】:
-
哦,我也忘了说logcat里连我的“oh no”的日志都没有打印出来,也就是说数组,“list”不为空? (这让我更加困惑!)
-
它说它返回一个文件列表或 null listFiles() 所以尝试 null 而不是 0
-
你好,activity终于打开了,但是listview是空的(说明我的目录不对?不明白怎么获取正确的目录)
-
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
-
下载目录中没有文件或者没有文件
标签: android android-listview nullpointerexception directory android-file