List all music in MediaStore with the PATHs

前端 未结 4 1727
刺人心
刺人心 2020-12-02 10:45

Ok so I\'ve been working on this project for a few days now and most of my time has been working out how to list all the music on a device in a LIST VIEW or something else,

4条回答
  •  感情败类
    2020-12-02 11:23

    I'm working on same project right now and already solved the problem.

    You will need a custom class to store your songs data:

    package YOUR_PACKAGE;
    
    public class Songs
    {
        private long mSongID;
        private String mSongTitle;
    
        public Songs(long id, String title){
            mSongID = id;
            mSongTitle = title;
        }
    
        public long getSongID(){
            return mSongID;
        }
    
        public String getSongTitle(){
            return mSongTitle;
        }
    }
    

    Then you have to define ArrayList in activity with List View which you will populate with data:

    private ArrayList arrayList;
    

    and in onCreate:

    arrayList = new ArrayList();
    

    Then you have to retrieve data from your device:

    public void YOUR_METHOD_NAME(){
        ContentResolver contentResolver = getContentResolver();
        Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor songCursor = contentResolver.query(songUri, null, null, null, null);
    
        if(songCursor != null && songCursor.moveToFirst())
        {
            int songId = songCursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
    
            do {
                long currentId = songCursor.getLong(songId);
                String currentTitle = songCursor.getString(songTitle);
                arrayList.add(new Songs(currentId, currentTitle, currentArtist));
            } while(songCursor.moveToNext());
        }
    }
    

    Then call this method from onCreate:

    YOUR_METHOD_NAME();
    

    And finally you have to create custom adapter class, define this adapter in onCreate (in activity with ListView) and set this adapter on your ListView object.

    I see that it was asked 3 years ago and the problem I think already solved, but maybe it will be usefull for someone. Thanks.

提交回复
热议问题