Reputation: 179
I am making an application which opens a file using another application. The problem is if the file name contains spaces there is an error-and exception is not showed -. I've tried String.replace(" ", "\\ ");
but does not work.
My code seems like
File f = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).
getAbsoluteFile() + "/MyFolder", file);
if (f.exists()) {
Uri path = Uri.fromFile(new File(f.getAbsolutePath().replace(" ", "\\ ")));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, getMimeType(file));
PackageManager pm = getPackageManager();
ComponentName component = intent.resolveActivity(pm);
if (component == null) {
Toast.makeText(
getApplicationContext(),
"There is not any application to open this file.",
Toast.LENGTH_SHORT).show();
Log.e("LaunchApp", "There is not any application to open this file.");
} else {
startActivity(intent);
}
}
File Path is like /storage/emulated/0/Download/MyFolder/Photos/My Photo.jpg;
Result: file:///storage/emulated/0/Download/MyFolder/Photos/My%5C%20Photo.jpg
Otherwise: file:///storage/emulated/0/Download/MyFolder/Photos/My/ Photo.jpg and does not work neither.
What i want: file:///storage/emulated/0/Download/MyFolder/Photos/My Photo.jpg If I "hardcoded" the path, is not success.
Thanks on advance!
Upvotes: 1
Views: 893
Reputation: 179
The issue was caused by MimeType method.
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url.replace(" ", ""));
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
I took out all spaces from url(File Path), and now MimeType does not return null and then, startActivity works fine.
Upvotes: 1
Reputation: 8519
You should replace "%20"
to "_"
because if you replace it to "\\ "
you'll be creating a sub path which might not exist.
f.getAbsolutePath().replace("%20", "_")
Upvotes: 0