Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Mediastore: How to efficiently retrieve all songs of a certain genre?

I know how to retrieve the genre of a particular song, (see getting the genres), but I want to retrieve all songs of a particular genre. Since "genre" does not seem to be one of the columns for a media item, I don't know how to do it in a single query, unlike artist or album. Is there an efficient method? Thanx!

like image 388
MBro Avatar asked Dec 14 '11 22:12

MBro


2 Answers

Uri uri = Audio.Genres.Members.getContentUri("external", genreID); 

String[] projection = new String[]{Audio.Media.TITLE, Audio.Media._ID};

Cursor cur = contentResolver.query(uri, projection, null, null, null);
like image 154
Alexander Mikhalevich Avatar answered Sep 17 '22 15:09

Alexander Mikhalevich


You can do this by putting together a content URI and querying the MediaStore. Here's some code borrowed from the Android music player:

String [] cols = new String [] {MediaStore.Audio.Genres.NAME};
Cursor cursor = MusicUtils.query(this,
                ContentUris.withAppendedId(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, Long.valueOf(mGenre)),
                cols, null, null, null);

This is the code in MusicUtils:

public static Cursor query(Context context, Uri uri, String[] projection,
        String selection, String[] selectionArgs, String sortOrder, int limit) {
    try {
        ContentResolver resolver = context.getContentResolver();
        if (resolver == null) {
            return null;
        }
        if (limit > 0) {
            uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
        }
        return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
     } catch (UnsupportedOperationException ex) {
        ErrorReporter.getInstance().putCustomData("UnsupportedOperationException", "true");
        return null;
    }

}
like image 24
christoff Avatar answered Sep 18 '22 15:09

christoff