How to determine MIME type of file in android?

Sushant Bhatnagar picture Sushant Bhatnagar · Dec 21, 2011 · Viewed 141.8k times · Source

Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.

I created a function for it

public static String getMimeType(File file, Context context)    
{
    Uri uri = Uri.fromFile(file);
    ContentResolver cR = context.getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String type = mime.getExtensionFromMimeType(cR.getType(uri));
    return type;
}

but when i call it, it returns null.

File file = new File(filePath);
String fileType=CommonFunctions.getMimeType(file, context);

Answer

Jens picture Jens · Dec 21, 2011

First and foremost, you should consider calling MimeTypeMap#getMimeTypeFromExtension(), like this:

// url = file path or whatever suitable URL you want.
public static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}