Question

I have already looked at these questions on 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

But none of them worked for my code. I am not sure why it doesn't work?

What I am trying to do is to create a listview that displays all of the files inside a specific folder. The specific folder I want to be displayed is the Download folder (the one you can see if you plug your phone into your USB). To clarify, on my PC, the directory looks like this:

This PC\Nexus 4\Internal storage\Download

Here is my code (in my onCreate method):

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);

I have tried

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()); 

I have also tried

File directory = Environment.getExternalStorageDirectory();
file = new File(directory+ "/Download");// + "/Test");

Though it still doesn't work.

My log cat says that there is a nullpointerexception starting on the line that declares the for loop:

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

Thank you very much in advance!

Était-ce utile?

La solution

I have figured out exactly what I did that was wrong. What JRowan told me was correct. In order to get the directory of my device's Download folder, then I need to use this piece of code:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 

Initially, it didn't work because I forgot to add this permission to my Android manifest:

android.permission.WRITE_EXTERNAL_STORAGE

So, to summarize, I forgot to write this crucial permission. Without it, the directory actually gets me to: /storage/emulated/0/download (which isn't what I want obviously).

Thanks to the two people who tried to answer my question!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top