Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentResolver always returns null

Tags:

android

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??

like image 734
Dunes Buggy Avatar asked Nov 17 '14 21:11

Dunes Buggy


People also ask

What does ContentResolver query () return?

The ContentResolver. query() client method always returns a Cursor containing the columns specified by the query's projection for the rows that match the query's selection criteria. A Cursor object provides random read access to the rows and columns it contains.

What is the use of ContentResolver in Android?

The Content Resolver behaves exactly as its name implies: it accepts requests from clients, and resolves these requests by directing them to the content provider with a distinct authority. To do this, the Content Resolver stores a mapping from authorities to Content Providers.


2 Answers

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

  • FileProvider API
  • FileProvider.GetUriForFile()

I hope this helps!

like image 185
Ashutosh Tiwari Avatar answered Oct 19 '22 05:10

Ashutosh Tiwari


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

like image 24
eghdev Avatar answered Oct 19 '22 03:10

eghdev