Get count of members of a given mediastore genre without loading extra cursor

558 views Asked by At

I have a list of all genres present in my device displayed in a RecyclerView, the contents of mediastore query being fetched onBindViewHolder. I also want to display the number of songs in each genre along with the names of the genre. I have the genre id and can get the count as

int count;
            String[] projection = {MediaStore.Audio.Genres.Members.AUDIO_ID};
            String selection = MediaStore.Audio.Genres.Members.IS_MUSIC + "!=0";
            Uri uri = MediaStore.Audio.Genres.Members.getContentUri("external", id);
            Cursor tempcursor = fragmentActivity.getContentResolver().query(uri, projection, selection, null, null);
            if(tempcursor != null) {
                count = tempcursor.getCount();
                tempcursor.close();
            }

However, since I am fetching the genre cursor contents in onBindViewHolder, I cannot have an extra query which would hamper with smoothness of scrolling. There is a field called MediaStore.Audio.Genres._COUNTbut it gives no such column found error during runtime. It will be really helpful if someone can point to a solution keeping scrolling acceptable and without changing my present app structure by a large margin. Thanks in advance

1

There are 1 answers

1
Theo On

This is the way I do it in my app New Playlist Manager

      public int getgenre_Count(Context context, long genreID) {
    final String track_id = MediaStore.Audio.Genres.Members._ID;
    final ContentResolver resolve = context.getContentResolver();
    Uri uri = MediaStore.Audio.Genres.Members.getContentUri("external",
            genreID);
    final String[] columns = {track_id};
    Cursor cur = resolve.query(uri, columns, null, null, null);
    int genrecnt = 0;
    if (cur != null && cur.moveToFirst()) {
        genrecnt = cur.getCount();
        cur.close();
    }
    return genrecnt;
}

I do this in the adapter and it behaves fine.