从MediaStore获取所有曲目

时间:2014-04-03 12:15:20

标签: android mediastore

我尝试从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();

但是我无法从光标读取值。当我运行此代码时

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

常量为空。

我必须使用哪些常量来获取上面结果中的值?

1 个答案:

答案 0 :(得分:2)

设置列和uri返回:

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;

获取所有曲目:

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;
}

现在遍历游标并根据返回的列提取字符串值。 您只能提取光标返回的列,这样会发生错误,因为我没有返回NUMBER_OF_SONGS。您必须确保光标也返回这一点 例如:

        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)));

你99%正确,但你的uri需要列布局。希望这有帮助