0

I want to list all the files on the SD card. I use a this code for it: myList = new ArrayList();

    String root_sd = Environment.getExternalStorageDirectory().toString();
    file = new File( "storage/" + root_sd ) ;
    Log.e(myLog, file.getName());
    File list[] = file.listFiles();

    for( int i=0; i< list.length; i++)
    {
        myList.add( list[i].getName() );
        Log.e(myLog, list[i].getName() + " : " + list[i].getTotalSpace());

    }

And I get a nullPointerException for it after I log the name. I tried an other file also:

   file = new File( root_sd ) ;

Ended with the same result.

So, how can I list the files properly? Thx for help!

gujci
  • 1,238
  • 13
  • 21
  • The external storage directory is not the external SD card be carefull – greywolf82 May 17 '14 at 13:16
  • Try this : http://stackoverflow.com/questions/5800981/how-to-display-files-on-the-sd-card-in-a-listview – vjdhama May 17 '14 at 13:19
  • Thank for the link, that solution seems easier than mine. Although the same problem appears. the 'new File("sompath")' returns a null, but im sure that the path is correct '(Environment.getExternalStorageDirectory().toString())' – gujci May 17 '14 at 17:32

1 Answers1

0
   ...//initing the variables

   String fileName = Environment.getExternalStorageDirectory().toString();
    title.setText(fileName);

    ArrayList<String> FilesInFolder = GetFiles(fileName);

    mList.setAdapter(new ArrayAdapter<String>(getActivity() , android.R.layout.simple_list_item_1 , FilesInFolder));

    mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // Clicking on items
        }
    });

and the function

   public ArrayList<String> GetFiles(String DirectoryPath) {
    ArrayList<String> MyFiles = new ArrayList<String>();
    File f = new File(DirectoryPath);

      f.mkdirs();
      File[] files = f.listFiles();
      if (files.length == 0)
          return null;
      else {
          for (int i=0; i<files.length; i++)
              MyFiles.add(files[i].getName());
      }

    return MyFiles;
}

If you want a different layout make an own ArrayAdapter

gujci
  • 1,238
  • 13
  • 21