Android List documents with Specific extension from SD Card

In previous application we had functionality to attach the document or file from SD card, to let user choose from number of available files and also in folders with specific extension is a challenging task,

So here is snippet of code that we used to list the documents matching with specific extension and too look into directory and sub directory, so at any place you place the document under any folder and this code will list it for you

First declare a ArrayList for the file list to hold and one SD card object to traverse through

private File sdcardObj=new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private ArrayList<String> filelist=new ArrayList<String>();

Now after this prepare one function that will recursively traverse through the folder and file list and list only the specific extension files for you, if you dont need that then you can remove and it will list all the items on your SD card

private void listFiles(File sdcard,ArrayList<String> filelist) {
         if(sdcard.isDirectory()){
             File[] files = sdcard.listFiles();

                     try {
                         for (File f : files){
                            if(!f.isDirectory()) {
                                 if(f.getName().endsWith(".doc")||  f.getName().endsWith(".txt")|| f.getName().endsWith(".docx")||f.getName().endsWith(".rtf")) {
                                     // Log.d(" FILES",f.getName());
                                    this.filelist.add(f.getAbsolutePath());

                                }
                              }
                            else {
                                 this.listFiles(f,this.filelist);
                             }
                     }
               } catch (Exception e) {
                      // TODO Auto-generated catch block
                     //e.printStackTrace();
            } 
      }
  }

You need to call this function in async task as it may take some more time if you SD card is more crowded with documents

When done you can pass on the arraylist you just filled with the valid extension files to display to view so it will look as

 

 

 

 

 

 

 

 

 

 

 

 

And you are done… thats it

About these ads

What you think ? Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s