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:estonia.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);
}
CodePudding user response:
A File can not be created from an URI string via the constructor call. Some escaping will not work as expected. Try instead:
Paths.get(uri).toFile()
If it still does not work, perhaps the file is not there or you are not allowed to access it, or the URI doesn't represent a file location. From the docs:
The default provider provides a similar round-trip guarantee to the java.io.File class. For a given Path p it is guaranteed that Paths.get(p.toUri()).equals( p.toAbsolutePath())
CodePudding user response:
Try below code
File oFile = new File(data.getData().getPath());
if (oFile.exists()){
Toast.makeText(this, "exist: " oFile.exists(), Toast.LENGTH_SHORT).show(); //returns true
openMap(oFile);
}else{
Log.w("File", "File does not exist");
}
Let me know if the problem not solved yet.