如何在android中对光标中的音乐文件进行排序

时间:2017-01-04 14:47:16

标签: android listview android-mediaplayer android-cursor

我正在创建音乐播放应用程序并且我从设备获取了音乐文件,但它并没有短路。

它显示如下(不按排序顺序)

Snapshot of App music listview which is not sorted

ListView显示歌曲的代码:

public class songlist extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private ListView lv_songlist;
public Cursor cursor;

private MediaCursorAdapter mediaAdapter = null;
private String currentFile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.songlist);

    lv_songlist = (ListView) findViewById(R.id.songlist);


    cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);

    if (null != cursor) {
        cursor.moveToFirst();

        mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
    }
}

private class MediaCursorAdapter extends SimpleCursorAdapter {

    public MediaCursorAdapter(Context context, int layout, Cursor c) {
        super(context, layout, c,
                new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
                new int[]{R.id.displayname, R.id.title, R.id.duration});
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView name = (TextView) view.findViewById(R.id.displayname);
        TextView duration = (TextView) view.findViewById(R.id.duration);

        name.setText(cursor.getString(
                cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));

        title.setText(cursor.getString(
                cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));

        long durationInMs = Long.parseLong(cursor.getString(
                cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));

        Duration d = new Duration();

        String durationInMin = d.convertDuration(durationInMs);

        duration.setText("" + durationInMin);

        view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.listitem, parent, false);

        bindView(v, context, cursor);

        return v;
    }
}


}

1 个答案:

答案 0 :(得分:1)

像这样创建字符串:

private String sortOrder = MediaStore.MediaColumns.DISPLAY_NAME+"";

并将此字符串传递给contentResolver.query方法的最后一个参数:

cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, sortOrder);