Pete Nelson
Pete Nelson

Reputation: 1338

Querying the MediaStore is coming up with results that don't appear to match

I'm new to Android development and I've been working on a custom music player for my own use. After quite a bit of searching, I finally tracked down some code I could use to search the MediaStore for music files. This is the code I'm using.

Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");

// Add in the filtering constraints
String [] keywords = null;
if (query != null) {
    String [] searchWords = query.split(" ");
    keywords = new String[searchWords.length];
    Collator col = Collator.getInstance();
    col.setStrength(Collator.IDENTICAL);

    for (int i = 0; i < searchWords.length; i++) {
        keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
    }


    for (int i = 0; i < searchWords.length; i++) {
        where.append(" AND ");
        where.append(MediaStore.Audio.Media.ARTIST_KEY + "||");
        where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ?");
    }
}

String selection = where.toString();

String[] projection = {
        BaseColumns._ID,   
        MediaStore.Audio.Media.MIME_TYPE, 
        MediaStore.Audio.Artists.ARTIST,
        MediaStore.Audio.Albums.ALBUM,
        MediaStore.Audio.Media.TITLE
};


Cursor cursor = this.managedQuery(
        uri,
        projection,
        selection,
        keywords,
        MediaStore.Audio.Media.TITLE);

If I search for "Laredo", I expect it to come back with just "The Streets of Laredo" by Johnny Cash. It's included in the results, but there's a couple dozen other songs being returned that don't seem to match my query at all.

The built-in music player seems to be doing the same thing, although it's returning even more unrelated matches. Is this the expected behavior? If it is, I can add some additional code to filter my list down to exact matches. If it's not, what am I doing wrong?

Upvotes: 1

Views: 1032

Answers (1)

Alexander Lucas
Alexander Lucas

Reputation: 22371

A bit of a longshot, but try parenthesizing your WHERE statement so that it reads where (title != '') AND (artist||title like ? AND artist||title like ?...)

I'm curious if logic is happening such that it reads "where title != ('' AND artist||title = ? ...) which, if it even parsed, would return some funky results.

That said, if you're seeing weird results with the built-in music player, which device/platform version(s) are you testing with?

Upvotes: 1

Related Questions