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

How to sort music files in cursor in android

我正在创建音乐播放器应用程序,我从设备中获取了音乐文件,但它不是短顺序。

是这样显示的(未排序)

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


}

像这样创建字符串:

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

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

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