MediaStore: get image data, thumbnail and folder

Lingviston picture Lingviston · Dec 12, 2012 · Viewed 15.7k times · Source

I have two lists. Let's call them AlbumsList and PicturesList.

  • The first one shows photo album cover (one of the images from it) it's name and number of pictures in it.
  • The second one shows all of the images contained in a chosen album.

I've already done it using File class but it works too slow and finds all of the images on device when I need only those from gallery. I've read about MediaStore content provider but have never used it. So I have 2 questions:

  1. How to find "photo albums" (folders in gallery containing pictures), thumbnails for them and number of pictures in them using MediaStore class? I think it's similar to "how to find file paths and thumbnails for all of the images in gallery?"
  2. How to get file paths and thumbnails for all of the images in particular folder using MediaStore class?

EDIT: It seems like MediaStore.Images.Media.DATA column contains the filepath, so I can get the album folder. MediaStore.Images.Media.Display_NAME looks like a filename but I'm not sure that it's always true. Can I get thumbnail data column it addition to these columns without making second query?

Answer

Lingviston picture Lingviston · Jun 16, 2013

Here the code I've written:

    Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String[] projection = { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME };

    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

    ArrayList<String> ids = new ArrayList<String>();
    mAlbumsList.clear();
    if (cursor != null) {
        while (cursor.moveToNext()) {
            Album album = new Album();

            int columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID);
            album.id = cursor.getString(columnIndex);

            if (!ids.contains(album.id)) {
                columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
                album.name = cursor.getString(columnIndex);

                columnIndex = cursor.getColumnIndex(MediaStore.Images.Media._ID);
                album.coverID = cursor.getLong(columnIndex);

                mAlbumsList.add(album);
                ids.add(album.id);
            } else {
                mAlbumsList.get(ids.indexOf(album.id)).count++;
            }
        }
        cursor.close();

It uses my ALbum class and previously declared var mAlbumsList but I think it's clear enough to understand how it works. Maybe it'll help someone.