F.M.
F.M.

Reputation: 285

Android correct way to get File from Uri

I pick a PDF from local archive using:

startActivityForResult(Intent.createChooser(new Intent().setType("application/pdf").setAction(Intent.ACTION_GET_CONTENT), getString(R.string.str_select_file)), request_id_archive);

and manage result:

    @Override
    protected void onActivityResult(int request_code, int result_code, Intent data) {
        super.onActivityResult(request_code, result_code, data);

        if (request_code == request_id_archive && result_code == RESULT_OK && data != null && data.getData() != null) {
            Uri myuri = data.getData();
            String mypath = myuri.getPath();
            File myfile = new File(mypath);
            Log.d("mylog1", uri.toString());
            Log.d("mylog2", uri.getPath());
            Log.d("mylog3", f.getPath());
            Log.d("mylog4", f.toString());
            Log.d("mylog5", Boolean.toString(f.exists()));
        }
        else {...}

It seems that the file is not succesfully created. Result of my Logs are:

Method file.exist() return me that the file do not exist. Why?

In other code I try to manage the file for many other operations:

...
InputStream inputStream = new FileInputStream(file);
...

But my app crash ang in Logcat I see:

java.io.FileNotFoundException: /document/raw:/storage/emulated/0/Download/20180702_121938.pdf (No such file or directory)

I'm testing my code on Android 7.

Upvotes: 4

Views: 1817

Answers (1)

bond benz
bond benz

Reputation: 81

You need to replace 'document/raw' with an empty string, so you need to add this code before accessing the file:

if(mypath.contains("document/raw:")){
    mypath = mypath.replace("/document/raw:","");
}

Upvotes: 5

Related Questions