Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android file chooser with specific file extensions

I need to show only 'pdf' files in my application when I run default File chooser I'm not able to filter file extensions.

    final Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT);
    getContentIntent.setType("application/pdf");
    getContentIntent.addCategory(Intent.CATEGORY_OPENABLE);

    Intent intent = Intent.createChooser(getContentIntent, "Select a file");
    startActivityForResult(intent, REQUEST_PDF_GET);

File chooser shows any kinds of files. I would like to show only pdf files. How can i filter files showed by File chooser.

like image 362
Nande kore Avatar asked Dec 10 '14 17:12

Nande kore


1 Answers

It's an unknown to you what user-installed file browser apps your intent may trigger. I think this is a case where's it's better to hand roll something. My approach was to

a) Find all files with a particular extension on external media with something like (I was looking for the .saf extension, so you'd alter for .pdf accordingly):

    public ArrayList<String> findSAFs(File dir, ArrayList<String> matchingSAFFileNames) {
    String safPattern = ".saf";

    File listFile[] = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
                findSAFs(listFile[i], matchingSAFFileNames);
            } else {
              if (listFile[i].getName().endsWith(safPattern)){
                  matchingSAFFileNames.add(dir.toString() + File.separator + listFile[i].getName());
                  //System.out.println("Found one! " + dir.toString() + listFile[i].getName());
              }
            }
        }
    }    
    //System.out.println("Outgoing size: " + matchingSAFFileNames.size());  
    return matchingSAFFileNames;
}

b) Get that result into a ListView and let the user touch the file s/he wants. You can make the list as fancy as you want -- show thumbnails, plus filename, etc.

It sounds like it would take a long time, but it didn't and you then know the behavior for every device.

like image 152
JASON G PETERSON Avatar answered Sep 22 '22 10:09

JASON G PETERSON