Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MediaStore query to get Artists without duplicates?

I would like to get all the artists names on my phone by using MediaStore ;Already I have the whole list but with duplicates of all entries due to multiple links songs/artists. Is there any way to use the query to get only one of each, without any duplicates?

There is my query :

    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    String[] projection = {
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DURATION
    };
    Cursor cursor = context.getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            null);

Thanks in advance !

like image 394
Jackyto Avatar asked Oct 17 '25 13:10

Jackyto


2 Answers

For people who are still looking for an answer to this, I'd suggest doing the following:

String[] mProjection =
         {
                MediaStore.Audio.Artists._ID,
                MediaStore.Audio.Artists.ARTIST,
                MediaStore.Audio.Artists.NUMBER_OF_TRACKS,
                MediaStore.Audio.Artists.NUMBER_OF_ALBUMS
         };

Cursor artistCursor = mContentResolver.query(
                MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
                mProjection,
                null,
                null,
                MediaStore.Audio.Artists.ARTIST + " ASC");  

Now you can query this cursor to get the name of all artists. There won't be any duplicates.
I understand that this is not the solution to "get unique values from MediaStore" in general. But it would solve this very specific problem.

Explanation:
You just have to query the right table, which in this case was the "Artist" table, while the op was querying the "Media" table.

Hope this helps someone.

like image 97
Anjani Avatar answered Oct 19 '25 04:10

Anjani


Using the keyword DISTINCT in the query returns non duplicate values For example, listing only album names when querying many audio numbers

        new String[] { "DISTINCT " + MediaStore.Audio.Playlists.Members.ALBUM_ID + " as _id"}

but I found you can only return one column

I kept it simple and did the following when looping through the cursor. Pass the value, in your case the artist,

    if (value.length() > 0) {
        // check if value already exists
        if (!listItems.contains(value)) {
            // doesn't exist, add it
            listItems.add(value);
        }

    }

This is a simple method. You can check this out in my app Playlist Manager on Google Play. I use this technique for selecting artists, years, etc.

like image 33
Theo Avatar answered Oct 19 '25 03:10

Theo