how to set MEDIASTORE to get image from specific folder on android

5.4k views Asked by At

So i have this code for getting images with mediastore :

int dataIndex = mMediaStoreCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA );

mMediaStoreCursor.moveToPosition(position);
String dataString = mMediaStoreCursor.getString(dataIndex);
Uri mediaUri = Uri.parse("file://" + dataString);
return mediaUri;

This good gets all the images in the pictures folder, i would like to change that to get all the images in a specific folder, which will be passed in as a string. e.g { android/picture/specificfolder/}

3

There are 3 answers

0
yotam hadas On

Check this post

It advice you to use cursor and pass the folder needed in the projection.

the relevant answer from teh post:

mediaCursor = getContentResolver().query( MediaStore.Files.getContentUri("external"),
                null,
                MediaStore.Images.Media.DATA + " like ? ",
                new String[] {"%YOUR_FOLDER_NAME%"},
                null);

0
tahsinRupam On

You can use following method -

public List<String> getFromSdcard()
{
    ArrayList<String> imagePaths = new ArrayList<String>();// list of file paths
    File[] listFile;
    File file= new 

    File(android.os.Environment.getExternalStorageDirectory(),"android/picture/specificfolder/");

    if (file.isDirectory())
    {
        listFile = file.listFiles();


        for (int i = 0; i < listFile.length; i++)
        {

            imagePaths.add(listFile[i].getAbsolutePath());

        }
    }
    return imagePaths;
}

to retreive the images use

List<String> sample = getFromSdcard();

    for(int i=0; i<sample.size() ; i++){
      final Uri image = Uri.parse("file://"+sample(i).toString());
    }
3
Vinod Kamble On
val DIRECTORY_NAME = "%your_folder_name%"

val selection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
    MediaStore.MediaColumns.RELATIVE_PATH + " like ? "
else MediaStore.Images.Media.DATA + " like ? "

val selectionArgs = arrayOf(APP_RESOURCE_DIRECTORY_NAME)

val cursor = context.contentResolver.query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        null,
        selection,
        selectionArgs,
        null)