I am trying to do a Media Player and the first step for that is to scan all the songs available in the external storage of the device. After that I will store them on a list, but I got stuck in this first point. (I am not familiar with Uri or Cursor so I don't really know how they work even after researching on google and Stackoverflow for a while, and maybe that is the problem)
I want to be able to store every song that the cursor gets in a list of a class Song, which will have artist, album, title, duration and path. I want to use the path later to reproduce the song with mediaPlayer.setDataSource(path);
but I do not know how to get it.
protected void getSongs() {
ContentResolver contentResolver = this.getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri,null,MediaStore.Audio.Media.IS_MUSIC + " = 1",null,null);
if (cursor!=null&&cursor.moveToFirst()){
//retrieve index of columns
int artistColumn=cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int albumColumn=cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int titleColumn=cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int durationColumn=cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
//get path somehow
}
else {
Toast.makeText(this, "Query failed", Toast.LENGTH_SHORT).show();
}
The method is not finished. I know I am missing a couple stuff but the only doubt that I cannot find is the path of the current cursor element.
Thanks in advance.
A cursor is in effect a dataset that was returned. Imagine it like a spreadsheet with rows(each track) and columns. Columns contain the separate pieces of data, a row represents one record.
each column is accessed by getting it's index ie position to the right in the spreadsheet table
private final String track_id = MediaStore.Audio.Media._ID;
private final String bucket_displayname = MediaStore.Audio.Media.BUCKET_DISPLAY_NAME;
private final String track_no = MediaStore.Audio.Media.TRACK;
private final String track_name = MediaStore.Audio.Media.TITLE;
private final String artist = MediaStore.Audio.Media.ARTIST;
private final String artist_id = MediaStore.Audio.Media.ARTIST_ID;
private final String duration = MediaStore.Audio.Media.DURATION;
private final String album = MediaStore.Audio.Media.ALBUM;
private final String composer = MediaStore.Audio.Media.COMPOSER;
private final String year = MediaStore.Audio.Media.YEAR;
private final String path = MediaStore.Audio.Media.DATA;
private final String date_added = MediaStore.Audio.Media.DATE_ADDED;
private final String genre = MediaStore.Audio.Media.GENRE;
private final String genre_id = MediaStore.Audio.Media.GENRE_ID;
and so on. Note there is a column called MediaStore.Audio.Media.DATA (apart from android10 when google decided to do away with this only to bring it back in 11) So when you loop around your cursor, you effectively read each row of your spreadsheet.