Accessing all images using MediaStore: An android provider

on

As an android developer, we need to access devices images for various purpose. To access images, android sdk provide a build in content provider, called MediaStore.

Here I will demonstrate how we can use MediaStore to access not only all photos but also map them into their corresponding albums.

 

1st off all we will need external storage read permission.

android.permission.READ_EXTERNAL_STORAGE

For loading album of photos, we need to load all images. And have to map thouse photos to sepecfic BUCKET_ID.

To load the photos, the uri will be: MediaStore.Images.Media.EXTERNAL_CONTENT_URI
We are fetching only these data by quering media store.

MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.ORIENTATION

with orderby: MediaStore.Images.Media.DATE_TAKEN + ” DESC”

For more information about those columns:
https://developer.android.com/reference/android/provider/MediaStore.Images.ImageColumns.html

Now full query will be:

Cursor cursor = MediaStore.Images.Media.query(mContext.getContentResolver(), uri, projectionPhotos, "", null, MediaStore.Images.Media.DATE_TAKEN + " DESC");

To map albumId with photos, we declear one hashmap.

HashMap<Integer, AlbumEntry> albumMap = new HashMap<>();

1st we are trying to load a album from our data structure(map) with the key(image bucketId): album = albumMap.get(bucketId);
If we found null object, then we will store that album for the 1st time:

album = new AlbumEntry(bucketId, bucketName, photo);
albumMap.put(bucketId, album);

Now we will add the a photo to that album:

photo = new PhotoEntry(bucketId, imageId, dateTaken, path, orientation);
album.addPhoto(photo);

Full source code:
https://github.com/ivancse58/androidphotos/

Leave a Reply

Your email address will not be published. Required fields are marked *