How to sort music files in cursor in android

1.2k views Asked by At

I am creting music player app and I got music files from device but it is not in shorted order.

It is displaying like this (Not in sorted order)

Snapshot of App music listview which is not sorted

Code which displays songs in 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

There are 1 answers

0
Pedo On BEST ANSWER

Create string like this :

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

And pass this string to last argument in contentResolver.query method's last parameter :

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