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);
}
2
Answers
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.
This did the trick and I got the actual file loaded.
Try below code
Let me know if the problem not solved yet.