0

I have a code in which user selects a file and program returns android.net.Uri for the selected file. Next, the program converts Uri to java.io.File. When i invoke File.exists() the program returns false. Why the program cannot interract with existing file?

(for example, i select 1.pdf on my microsd card, but the result will be the same if i select any other file from internal storage)

public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/pdf");

    startActivityForResult(intent, 123);
}

@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);
    if (requestCode == 123
            && resultCode == Activity.RESULT_OK) {

        if (resultData != null) {
            Uri uri = resultData.getData();
            try {
                File f=new File(uri.getPath());

                Log.e(TAG,"File object "+f.getAbsolutePath()); //returns /document/9016-4EF8:1.pdf
                Log.e(TAG,"File exists "+f.exists()); //returns false

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Dmitry
  • 115
  • 4
  • `Next, the program converts Uri to java.io.File.`. That is a bad habit. Dont do that. And not possible on Android Q. – blackapps Jun 12 '20 at 14:39
  • `Next, the program converts Uri to java.io.File.`. Ehhh... Uri.getPath() does not deliver a file system path to begin with. Look at its value to see. `/document/9016-4EF8:1.pdf` is not a valid path. You should look at Uri.toString() to see what you got. – blackapps Jun 12 '20 at 14:41
  • "That is a bad habit. Dont do that." that's because of Apache PdfBox. That lib works with File classes – Dmitry Jun 12 '20 at 14:42

0 Answers0