Search code examples
androidsd-carddocuments

How to scan SD card for particular extension of files in android?


I am working on a project which contains a module to scan pdf, doc xls files from sd card and make list of them. I also want to make list of folders only.

As I am very new to android. Anyone have idea of achieving this.

Here is my code:

public class MediaScannerWrapper implements  
MediaScannerConnection.MediaScannerConnectionClient {
    private MediaScannerConnection mConnection;
    private String mPath;
    private String mMimeType;

    // filePath - where to scan; 
    // mime type of media to scan i.e. "image/jpeg". 
    // use "*/*" for any media
    public MediaScannerWrapper(Context ctx, String filePath, String mime){
        mPath = filePath;
        mMimeType = mime;
        mConnection = new MediaScannerConnection(ctx, this);
    }

    // do the scanning
    public void scan() {
        mConnection.connect();
    }

    // start the scan when scanner is ready
    public void onMediaScannerConnected() {
        mConnection.scanFile(mPath, mMimeType);
        Log.w("MediaScannerWrapper", "media file scanned: " + mPath);
    }

    public void onScanCompleted(String path, Uri uri) {
        // when scan is completes, update media file tags
    }
}

Solution

  • public void walkdir(File dir) {
        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
    
                  }
                }
            }
        }    }
    

    To search on the whole sdcard call this function usingwalkdir(Environment.getExternalStorageDirectory());