11

I'm trying to get the content type of a local file on my android device. My code is

File file = new File(uploadPath.replace("file://",""));
Uri uri = Uri.fromFile(file);
ContentResolver contentResolver = getApplicationContext().getContentResolver();
String type = contentResolver.getType(uri);

My upload path is file:///storage/emulated/0/DCIM/Camera/20141016_181148.jpg. However, I always get my type as null. Why is that??

Dunes Buggy
  • 1,779
  • 1
  • 21
  • 41

4 Answers4

4

If you're working with latest coding standards, there are a lot of changes in terms of how the storage is managed and we access it. To answer your question, you got to replace Uri uri = Uri.fromFile(file); with below code:

Java:

 Uri uri = FileProvider.getUriForFile(
                            context,
                            context.getPackageName() + ".provider",
                            file
                        );

Kotlin:

val uri = FileProvider.getUriForFile(
                                context,
                                context.packageName + ".provider",
                                file
                            )

Don't forget to check the official documentation on

I hope this helps!

Ashutosh Tiwari
  • 424
  • 3
  • 13
  • Throws an exception for me, 'Couldn't find meta-data for provider with authority com.test.app.provider'. In my case the file lives in my apps sandbox, so I doubt I need to use the FileProvider API. Uri.fromFile(file) works fine, however I cannot get the contentType. – lostintranslation Aug 06 '21 at 14:15
  • 1
    @lostintranslation You really have to read over the [documentation](https://developer.android.com/reference/androidx/core/content/FileProvider) for this to understand. Using FileProvider also requires adding code to your manifest file also. – lasec0203 Aug 21 '21 at 08:56
2

The content resolver will return null if the uri scheme is not content://

m_drazzi
  • 106
  • 1
  • 8
1

to get the type of a file, look in there : How to determine MIME type of file in android?

Reasons about possible null value:

What causes Android's ContentResolver.query() to return null?

from what i can see the uri is probably incorrect.

Community
  • 1
  • 1
tangerine
  • 836
  • 1
  • 8
  • 14
0

in kotlin

get the mime with ContentResolver

var cr:ContentResolver = context.contentResolver
    var mime = cr.getType(uri)

the results will look like this: mime = "image/jpeg"

Hezy Ziv
  • 3,652
  • 2
  • 14
  • 8