Search code examples
androidandroid-emulatorandroid-contentproviderandroid-sdcardandroid-contentresolver

Content Resolver Query is not finding music on sd-card


I have constructed a simple query to find music on the sdcard of the Android emulator. I am using Android Studio. I placed 3 songs on the sdcard using adb push. However, the query is not finding the music files. Here is an image of the files on the sdcard in the Music folder:

enter image description here

Here is the code that I am using to perform the query:

    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

    // Now we can iterate over the results, first checking that we have valid data:
    if(musicCursor!=null && musicCursor.moveToFirst()){

        // We first retrieve the column indexes for the data items that we are interested in for each song
        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);

        // then we use these to create a new Song object and add it to the list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            allSongsPlaylist.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }

musicCursor is not null, but musicCursor.moveToNext() returns 0.

What am I doing wrong? The music files are obviously there on the sdcard, but the query doesn't see them. If I change the content URI to INTERNAL_CONTENT_URI, the query is finding files in internal storage (e.g. piezo alarm), but not my music files.


Solution

  • What am I doing wrong?

    If I had to guess, you are assuming that MediaStore knows about those files.

    MediaStore, on its own, only indexes external storage occasionally. It has no knowledge of files that you push there via adb.

    For lightweight testing, grab yourself an app from the Play Store that triggers a reindexing round. I used to use this app, but apparently it does not support Android 4.4+. There are plenty of others, like this one, that may work for you. Or, wait a day and try your tests again tomorrow, and they may get picked up automatically by then.

    Developers that write files to external storage programmatically should use MediaScannerConnection and scanFile() to get those files indexed by MediaStore.