Question

I try to get all tracks from MediaStore.

Cursor cursor = managedQuery(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, null, null, null, null);

while (cursor.moveToNext())
{
    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.AudioColumns._ID));

    String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));

    String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));

    String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));

    int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));

}

cursor.close();

But I can't read values from cursor. When I run this code

MediaStore.Audio.AudioColumns.TITLE, 
MediaStore.Audio.AudioColumns.ALBUM, 
MediaStore.Audio.AudioColumns.ARTIST and 
MediaStore.Audio.AudioColumns.DURATION 

constants is null.

Which constants I must use to get values in result above?

Was it helpful?

Solution

set up columns and uri to return:

final String track_id = MediaStore.Audio.Media._ID;
final String track_no = MediaStore.Audio.Media.TRACK;
final String track_name = MediaStore.Audio.Media.TITLE;
final String artist = MediaStore.Audio.Media.ARTIST;
final String duration = MediaStore.Audio.Media.DURATION;
final String album = MediaStore.Audio.Media.ALBUM;
final String composer = MediaStore.Audio.Media.COMPOSER;
final String year = MediaStore.Audio.Media.YEAR;
final String path = MediaStore.Audio.Media.DATA;
final String date_added = MediaStore.Audio.Media.DATE_ADDED;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

To get all tracks:

public Cursor getTrackTrackcursor(Context context, Cursor cursor) {
    // gets all tracks
    ContentResolver cr = context.getContentResolver();
    final String[] columns = { track_id, track_no, artist, track_name,
            album, duration, path, year, composer };
    cursor = cr.query(uri, columns, null, null, null);
    return cursor;
}

now loop through the cursor and extract the string values according to the columns returned. You can only extract columns which have been returned by the cursor so an error would occur as I did not return NUMBER_OF_SONGS. You would have to ensure this is also returned by the cursor For example:

        String stralbum = (c.getString(cursor
                .getColumnIndex(MediaStore.Audio.Albums.ALBUM)));
        String strartist = (cursor.getString(cursor
                .getColumnIndex(MediaStore.Audio.Albums.ARTIST)));
        String stryear = (cursor.getString(cusrsor
                .getColumnIndex(MediaStore.Audio.Albums.FIRST_YEAR)));
        String strnosongs = (cursor.getString(cursor
                .getColumnIndex(MediaStore.Audio.Albums.NUMBER_OF_SONGS)));

You are 99% correct but your uri needs the column layout. Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top