Android 在listview中显示文件名时出现NullPointerException?

Android 在listview中显示文件名时出现NullPointerException?,android,android-listview,nullpointerexception,directory,android-file,Android,Android Listview,Nullpointerexception,Directory,Android File,我已经研究了有关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/h

我已经研究了有关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
但是没有一个是为我的代码工作的。我不知道为什么它不起作用

我试图做的是创建一个listview,显示特定文件夹中的所有文件。我想显示的特定文件夹是下载文件夹,如果您将手机插入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 directory = Environment.getExternalStorageDirectory();
file = new File(directory+ "/Download");// + "/Test");
尽管它仍然不起作用

我的日志猫说在声明for循环的行上有一个nullpointerexception:

for( int i=0; i < list.length; i++)

提前非常感谢

我已经弄清楚我到底做了什么,那是错的。JRowan告诉我的是正确的。为了获取设备下载文件夹的目录,我需要使用以下代码:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 
最初,它不起作用,因为我忘了将此权限添加到我的Android清单:

android.permission.WRITE_EXTERNAL_STORAGE
总而言之,我忘了写这个重要的许可。没有它,目录实际上让我进入:/storage/simulated/0/download,这显然不是我想要的


感谢两个试图回答我问题的人

哦,我还忘了说它甚至没有在logcat中打印出我的日志,这意味着数组列表不是空的?这让我更加困惑!它说它返回一个文件列表或null listFiles,因此尝试null而不是0Hello,活动最终打开,但listview为空,这意味着我的目录错误?我不知道如何获得正确的目录.Environment.getExternalStoragePublicDirectoryEnvironment.directory\u下载;或者下载目录中没有文件
android.permission.WRITE_EXTERNAL_STORAGE