Using MediaStore
One of the Google-recommended alternatives to working directly with external storage is to use MediaStore
. MediaStore
, unfortunately, has never had particularly good documentation. And, some aspects of using MediaStore
changed in Android 10.
For general-purpose apps, the Storage Access Framework is a better solution for storing content. However, if your app has a particular focus on audio, video, or image media, then MediaStore
is well worth consideration.
What Not To Do
Due to the shortage of documentation, proper use of MediaStore
has always been a mess, rife with anti-patterns.
The biggest anti-pattern involves the use of the DATA
column. Too many developers try using query()
on a ContentResolver
, given a MediaStore
Uri
, to get the DATA
column. Those developers then treat the result as a filesystem path to access the media.
However:
- There is no requirement that the
DATA
column have a value - There is no requirement that the
DATA
column have a filesystem path - There is no requirement that the filesystem path in the
DATA
column be a file that you can access, even withREAD_EXTERNAL_STORAGE
And, on Android 10, the MediaStore
specifically will redact the DATA
column from any query results.
To get a Uri
that you can use with ContentResolver
for things like openInputStream()
:
- Query for the
_ID
column - Use
ContentUris.withAppendedId()
to assemble aMediaStore
Uri
from the baseUri
that you used in thequery()
and that ID value returned by thequery()
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.