8

I am launching an intent to launch a file picker where a user can choose a pdf file to use and upload to a server

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent,1);

when they pick a file it returns to onActivityResult where I look at the Uri of the file to see if it contains .pdf

if(requestCode == 1 && resultCode == RESULT_OK){
    Uri filePath = data.getData();
    File file = new File(filePath.getPath());
    if(filePath.toString().contains(".pdf")){
        if(file.length() <= 1048576){
            de.setPDFUri(filePath.toString());
        }else{
            Toast.makeText(this,"PDF cannot be more than 1 MB, please select another", Toast.LENGTH_SHORT).show();
        }
    }else{
        Toast.makeText(this,"Can only upload PDF files", Toast.LENGTH_SHORT).show();
    }
}

however this only works on some file manager apps (Astro,Explorer), most of the time I get a return like this

file:///storage/sdcard0/Download/20131231103232738561744.pdf

and on other programs (built in apps from manufacturer are the only ones I have seen so far) I get a return like this

content://media/external/file/109

which obviously does not tell me anything about the file and the type it is and returning the ContentProvider info for that file.

Is there a way to only let the user select .pdf files by sending something in the intent or a way to check the uri and make sure it is a .pdf file?

tyczj
  • 71,600
  • 54
  • 194
  • 296
  • This question gives some ideas as to how you might get the file path from a content URI: http://stackoverflow.com/questions/20067508 – NigelK Feb 12 '14 at 22:00

2 Answers2

-1

You can restrict the type of file that can be selected from the intent by specifying the file MIME Type in setType function. For restricting the user from selecting only the PDF files you can specify:

intent.setType("application/pdf");

Dani Akash
  • 6,828
  • 3
  • 35
  • 47
-1

intent.setType("application/pdf");