Search code examples
javaandroidimageandroid-cursormediastore

Accessing recent images in a folder using MediaStore


I am currently using this code to access the recent images from /DCIM/ folder -

final Cursor cursor = chatActivity.this.getContentResolver()
                .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                        null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");

and then get the images by

if (cursor.moveToFirst()) {
    String imageLocation = cursor.getString(1);
    File imageFile = new File(imageLocation);
    if (imageFile.exists()) {
        Bitmap bm = BitmapFactory.decodeFile(imageLocation);
    }
}

and then using cursor.moveToNext() to access the next image.

But if I have to access the images in another folder (like /MyFolder/Images/) in a similar fashion, using MediaStore and Cursor then what should be done?

I have looked at Get MediaStore path of a Specific Folder and Displaying images from a specific folder on the SDCard using a gridview, they don't answer my question.


Solution

  • With that code you are not only getting images from /DCIM/ folder but from all folders. If you want to get images from specific folder you can use something like this:

    final Cursor cursor = chatActivity.this.getContentResolver()
                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, MediaStore.Images.Media.DATA + " like ?",
                            "%" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/%", MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");