Search code examples
javaandroidmp3mime-typesandroid-contentresolver

Android app Mp3 file mimetype resolving to null


I am attempting to get the mimetype of an mp3 stored in Downloads. The problem is that mimetype always comes back null. I am unsure why. Note, making the extension lowercase (.mp3) doesn't make a difference.

String filePath = "/storage/emulated/0/Download/song.MP3";

File file = new File(filePath);
Uri uri2 = Uri.fromFile(file);

//will display /storage/emulated/0/Download/song.MP3
Log.d("file type as string",file.toString());

//will display file:///storage/emulated/0/Download/song.MP3
Log.d("uri type as string",uri2.toString());


ContentResolver cR = getApplicationContext().getContentResolver();
String mime = cR.getType(uri2);

//mime is null always displays
if(mime == null){
    Log.d("result", "mime is null");
} else{
    Log.d("mime", mime);
}

String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(filePath);
String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);


System.out.println("extension:" +extension); //displays MP3
System.out.println("mimetype:" + mimetype); //displays null

Solution

  • Check the following piece of code. You will come to know why you were not getting the required output.

        String type = null;
        String extension = "mp3";
    
        type = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    
        Log.d(TAG,"mime type1 "+type);
    
        extension = "MP3";
    
        type = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    
        Log.d(TAG,"mime type2 "+type);
    

    If you were not able to make any difference based on making the file extension in lowercase , consider using the

    File filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File mov = new File(filesDir,"song.mp3");
    

    and construct the uri using the file's absolute path instead of hardcoding the path.