Get the file extension of the selected file with the goal

I launch the intention to run a file collector where the user can select a pdf file to use and upload to the server

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

when they select a file, it goes back to onActivityResultwhere I look at the Urifile 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 in some applications with a file manager (Astro, Explorer), most of the time I get such a return

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

and on other programs (embedded applications from the manufacturer are the only ones I've seen so far). I get such a refund

content://media/external/file/109

which obviously tells me nothing about the file and its type, and returns ContentProviderinformation for that file.

.pdf, - uri , .pdf?

+7
2

, , MIME Type setType. PDF, :

intent.setType("application/pdf");

-1

intent.setType( "/PDF" );

-1

Source: https://habr.com/ru/post/1526624/


All Articles