My code works correctly while opening a file in sdcard. However, if I open a filename with white space then error occurs (example: Path - "/sdcard/download/hello hi.jpg").
I tried string.replace(" ","%20"); it doesn't work
try {
File file = new File(paths);
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(paths));
if (!mimeType.equals("")) {
intent.setDataAndType(path, mimeType);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(this, "Unsupported Format to Open", Toast.LENGTH_SHORT).show();
}
}
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No Application Available to View this File", Toast.LENGTH_SHORT).show();
} catch(Exception e) {
Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
}
Please help
Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.
Spaces are not supported by all operating systems or by command line applications. A space in a filename can cause errors when loading a file or when transferring files between computers. Common replacements for spaces in a filenames are dashes (-) or underscores (_).
Java per se handles spaces in filenames just fine with no escaping or anything.
Try:
Uri uri = Uri.parse(paths);
File file = new File(uri.getPath());
Uri.parse
fixes all the whitespace/backslash/illegal character issues in paths and produces a "good" uri.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With