File does not exist exception although file does exist

Issue

I need to user to choose a file from storage. Once user chooses the file I can’t do anything with it because it comes back with an exception "File does not exist", although it most certainly does. Permissions are granted and I even take persistent URI permission.
This sample code is not the prettiest, I know but it still shouldn’t give me that excpetion I think. Did I write something wrong or that could cause this problem?

Currently this sample code doesn’t throw an exception but if statement fails and logs "File does not exist". I need it to pass if statement and call openMap(). If I were to remove the if statement I would get org.mapsforge.map.reader.header.MapFileException: file does not exist: content:/com.android.externalstorage.documents/document/primary%3Aestonia.map

    final ActivityResultLauncher<Intent> sARL = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
    @Override
    public void onActivityResult(ActivityResult result) {
        if (result.getResultCode() == Activity.RESULT_OK){
            Intent data = result.getData();
            assert data != null;
            Uri uri = data.getData();
            File oFile = new File(uri.getPath());
            getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (new File(uri.getPath()).exists()){
                openMap(oFile);
            }else{
                Log.w("File", "File does not exist");
            }

        }
    }
});

public void openFileDialog(){
    Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    data.setType("*/*");
    data = Intent.createChooser(data, "Choose tile");

    sARL.launch(data);
}

Solution

The problem was with the Uri. If I hard code path to the file then everything is fine, but with file choosing intent I can’t actually access the real file path, as far as I know. File contents can still be read but I needed the path.

File oFile = new File(Environment.getExternalStorageDirectory() + filePath)

This did the trick and I got the actual file loaded.

Answered By – Topstiks

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published