Sumit Sharma
Sumit Sharma

Reputation: 1867

How to list SD card folders and files folders and files programmatically

I'm a newbie in android. I got an application in which I had list all SD files and folders which include doc,pdf,xls,jpg etc.

How to get Folder Name and File Name of all Folders and files present in my SD card programmatically in android?

I'm using this code but unable to get folder name(root folders and sub folders).

String pdfPattern = ".pdf";         
File listFile[] = dir.listFiles();
  if (listFile != null) 
       {
         for (int i = 0; i < listFile.length; i++) 
{ if (listFile[i].isDirectory()) { walkdir(listFile[i]); } else { if(listFile[i].getName().endsWith(pdfPattern)) { //Do what ever u want mArrayList.add(listFile[i].getName()); Log.v("", "--------- "+listFile[i].getName()); } } } ArrayAdapter songList = new ArrayAdapterthis,android.R.layout.simple_list_item_1,mArrayList); mlistview.setAdapter(songList);

Upvotes: 3

Views: 4919

Answers (1)

Andro Selva
Andro Selva

Reputation: 54332

You should try this sample file explorer.

And this is the method that traverses through the sdcard to fetch the list of files and directories.

private void getDir(String dirPath)

{

 myPath.setText("Location: " + dirPath);



 item = new ArrayList<String>();

 path = new ArrayList<String>();



 File f = new File(dirPath);

 File[] files = f.listFiles();



 if(!dirPath.equals(root))

 {



  item.add(root);

  path.add(root);



  item.add("../");

  path.add(f.getParent());



 }

Upvotes: 2

Related Questions