blganesh101
blganesh101

Reputation: 3695

Unable to load content from File URI

Hi i have a media file URI and i want to determine the mimetype and invoke appropriate activity in a generic way, Following is my code.

mediaUri = Uri.parse(filePath);

String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

Intent viewMediaIntent = new Intent();
viewMediaIntent.setAction(Intent.ACTION_VIEW);
viewMediaIntent.setDataAndType(mediaUri,mimeType);
viewMediaIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(viewMediaIntent);

Now the problem is few of the file uris are not working. But the same uri if converted to http uri and load from browser they are working fine. or any other app is able to load them,

Sample URIs which doesn't work
file:///storage/emulated/0/Samsung/Image/001.JPG file:///storage/emulated/0/Samsung/Music/Over the horizon.mp3

Error:

09-30 12:07:44.531: I/System.out(26771): Item Selected: file:///storage/emulated/0/Samsung/Image/001.JPG`
09-30 12:07:44.531: I/System.out(26771): mime type: null`
09-30 12:07:44.534: D/AndroidRuntime(26771): Shutting down VM`
09-30 12:07:44.534: W/dalvikvm(26771): threadid=1: thread exiting with uncaught exception (group=0x41e50ac8)`
09-30 12:07:44.545: E/AndroidRuntime(26771): FATAL EXCEPTION: main`
09-30 12:07:44.545: E/AndroidRuntime(26771): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/Samsung/Image/001.JPG flg=0x14000000 }`
09-30 12:07:44.545: E/AndroidRuntime(26771):    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1622)`
09-30 12:07:44.545: E/AndroidRuntime(26771):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)`

Upvotes: 0

Views: 1109

Answers (2)

Guerneen4
Guerneen4

Reputation: 728

You can get the extension in a more elegant way simply by calling the getFileExtensionFromUrl(url) method on MimeTypeMap like this

public static String getMimeType(String url)
  {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }
    return type;
  }

Upvotes: 1

blganesh101
blganesh101

Reputation: 3695

I figured it out.

String mimeType;
if (uri.toString().lastIndexOf(".") != -1) {
String ext = uri.toString().substring(
    uri.toString().lastIndexOf(".") + 1);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
mimeType = mime.getMimeTypeFromExtension(ext.toLowerCase());
} else {
mimeType = null;
}

With this method i'm able to get the correct mimetype and load works fine.

Upvotes: 2

Related Questions