Selecting an Android file with specific file extensions

I only need to show "pdf" files in my application when I run by default. File selection. I cannot 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);

      

Selecting a file shows any files. I would like to show only PDF files. How can I filter the files shown by file selection.

+3


source to share


1 answer


It is unknown what custom file browser applications can run. I think this is the case when it is better to give something. My approach was

a) Find all files with a specific extension on external media with something like (I was looking for the .saf extension, so you would change to .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 this result in ListView

and let the user touch the file he / she wants. You can make the list as fancy as you want - show thumbnails, plus filename, etc.

It looks like it will take a long time, but it doesn't and you then know the behavior for each device.

+4


source







All Articles