Search code examples
androidaudioandroid-contentprovidermediastore

MediaStore.Audio retrieve list of all the directories that contain audios


I am trying to get a list of all the directories that contain audios. Here is the code that I am using:

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection   = new String[]{MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.DISPLAY_NAME};
    String   sortOrder    = MediaStore.Audio.Media.DISPLAY_NAME + " ASC";
    CursorLoader cursorLoader = new CursorLoader(context,MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection,null,null,sortOrder);
    return cursorLoader;
}

MediaStore.Audio.Media.DATA gives me a list of all the audio files with their filepaths (with their names appended).

MediaStore.Audio.Media.Display_Name gives me the titles of the files.

However, what I want is to run a query that returns me a list of all the folders/directories (their path, name, and count of audios) that contain audio content. Any help is appreciated.


Solution

  • I was able to retrieve a list of all the folders/directories containing audios from the device. By using the following code.

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String[] projection = new String[]{"COUNT(" + MediaStore.Files.FileColumns.DATA + ") AS totalFiles",
                MediaStore.Files.FileColumns.MEDIA_TYPE,
                MediaStore.Files.FileColumns.PARENT,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.DISPLAY_NAME
                };
    
        String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + " = " + MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO +
                " OR "+ MediaStore.Files.FileColumns.MEDIA_TYPE + "=" + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO +
                ") GROUP BY (" + MediaStore.Files.FileColumns.PARENT;
    
        String sortOrder = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
    
        CursorLoader cursorLoader = new CursorLoader(context, MediaStore.Files.getContentUri("external"), projection, selection, null, sortOrder);
        return cursorLoader;
    }
    

    This piece of code makes and returns a cursor that Queries content provider with all the files having Media_Type as audio plus count of audios in every folder plus the path and name of the folders.