使用游标适配器在列表视图中获取歌曲

时间:2017-01-20 20:49:14

标签: android listview simplecursoradapter android-cursoradapter

我想从媒体商店获取歌曲标题到列表视图,有人可以解释我代码中的错误吗?

public class MainActivity extends AppCompatActivity {
    Cursor cursour;
    ContentResolver cr = this.getContentResolver();
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
    Cursor cur = cr.query(uri, null, selection, null, sortOrder);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur, new String[] {
                "MediaStore.Audio.Media.EXTERNAL_CONTENT_URI"
            },
            new int[] {
                android.R.id.text1
            }, 0);
        ListView lv = (ListView) findViewById(R.id.songlist);
        lv.setAdapter(adapter);
    }
}

1 个答案:

答案 0 :(得分:0)

使用此功能将歌曲导入列表视图

public void getAudioList() {
    String orderBy = MediaStore.Audio.Media.TITLE ;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
    Cursor mCursor = getContentResolver().query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media._ID }, selection, null, orderBy);

    int count = mCursor.getCount();
    while (mCursor.moveToNext()) {
        mSongsList.add(mCursor.getString(mCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
        SongsPath.add(mCursor.getLong(mCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));
    }
    mCursor.close();
}

    lv = (ListView) findViewById(R.id.list);
    getAudioList();
    ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mSongsList);
    lv.setAdapter(arrayAdapter);