Search code examples
androidlistviewsimplecursoradapterandroid-cursoradapter

Using cursor Adapter to get songs in a list view


I want to get song titles from media store to a list view can someone explain me whats wrong in the code ?

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

Solution

  • Use this to get songs into list view

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