12

Anyone know how to add playlists to Android in code?

I kind of get that I have to insert it into the content resolver but do I have to just put the song id in or do I have to put all of the song's data in?

I have been looking for sample code but haven't found any yet.

EDIT: Found an answer here is how I do it:

  public static void addToPlaylist(ContentResolver resolver, int audioId) {

        String[] cols = new String[] {
                "count(*)"
        };
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", YOUR_PLAYLIST_ID);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        final int base = cur.getInt(0);
        cur.close();
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base + audioId));
        values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audioId);
        resolver.insert(uri, values);
    }

   public static void removeFromPlaylist(ContentResolver resolver, int audioId) {
       Log.v("made it to add",""+audioId);
        String[] cols = new String[] {
                "count(*)"
        };
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", YOUR_PLAYLIST_ID);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        final int base = cur.getInt(0);
        cur.close();
        ContentValues values = new ContentValues();

        resolver.delete(uri, MediaStore.Audio.Playlists.Members.AUDIO_ID +" = "+audioId, null);
    }
shaneburgess
  • 15,702
  • 15
  • 47
  • 66
  • 4
    I'm trying to understand the code... In the addToPlaylist, are you actually setting PLAY_ORDER property to + ? Does that mean that PLAY_ORDER is not a track index, or that audioId is not unique identifier of the song in the device? – Jaroslav Záruba Nov 07 '10 at 17:46
  • Also, what's the playlistId supposed to be? This code seems to only add items to playlists - is there a way to actually *create* a playlist? – Yang Jun 27 '11 at 01:58
  • 1
    If you solved the problem yourself please move create an answer and mark it as accepted. – Nicklas A. Jul 10 '11 at 19:19
  • 2
    You should repost your answer as an answer.. Otherwise your question shows up in Unanswered. – Thomas Dignan Jul 12 '11 at 16:27
  • how to fetch YOUR_PLAYLIST_ID – Ankit Srivastava Jun 05 '14 at 07:57

4 Answers4

12

To get the question out of "not answered" I have pasted the OP's code here:

 public static void addToPlaylist(ContentResolver resolver, int audioId) {

        String[] cols = new String[] {
                "count(*)"
        };
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", YOUR_PLAYLIST_ID);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        final int base = cur.getInt(0);
        cur.close();
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base + audioId));
        values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audioId);
        resolver.insert(uri, values);
    }

   public static void removeFromPlaylist(ContentResolver resolver, int audioId) {
       Log.v("made it to add",""+audioId);
        String[] cols = new String[] {
                "count(*)"
        };
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", YOUR_PLAYLIST_ID);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        final int base = cur.getInt(0);
        cur.close();
        ContentValues values = new ContentValues();

        resolver.delete(uri, MediaStore.Audio.Playlists.Members.AUDIO_ID +" = "+audioId, null);
    }
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
  • Thanks, I was not sure if I could answer my own questions back then :) – shaneburgess Jul 15 '11 at 23:21
  • any idea how to create a new playlist by name? – Ivan G. Oct 11 '11 at 22:58
  • 2
    @aloneguid You can try: public static void createPlaylist(ContentResolver resolver, String pName) { Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI; ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Playlists.NAME, pName); Uri newPlaylistUri = resolver.insert(uri, values); Console.debug(TAG, "newPlaylistUri:" + newPlaylistUri, Console.Liviu); } – Ungureanu Liviu Feb 15 '12 at 20:07
  • ow to fetch YOUR_PLAYLIST_ID – Ankit Srivastava Jun 05 '14 at 10:01
2

To answer Jaroslav Záruba comment, the code is better with the PLAY_ORDER of added track set as follows:

cur.moveToLast();
final int base = cur.getInt(cur.getColumnIndex(Playlists.Members.PLAY_ORDER));
cur.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, 
      Integer.valueOf(base + 1));

Two major things change : We use the last element of the playlist (cur.moveToLast()) and we add 1 to its PLAY_ORDER value to determine the new track's PLAY_ORDER. The point is to have successive tracks in the playlist.

You can also add 10 for example so that you can insert tracks before or after your new track. I also changed the way we get the id of track. Indeed we don't want to have any problem getting wrong data so we specify the column we want.

Vince
  • 1,570
  • 3
  • 27
  • 48
1

This is corrected code which remove song from Playlist:

public static void removeFromPlaylist(ContentResolver resolver, int audioId) 
{
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", YOUR_PLAYLIST_ID);
resolver.delete(uri, MediaStore.Audio.Playlists.Members._ID +" = "+audioId, null);
}
Michal
  • 2,071
  • 19
  • 30
0

Use this the code itself is self explanatory. It will add song with given id = songID to playlist with name playlistName

If playlist already exist it will add to existing one or it will create new and then add song to it

 /**
     * This function add song with id songID to playlist playlistName
     * if playlist does exist it will add to exiixting one or it will create new
     *
     * @param playlistName
     * @param songID
     */
    private void addToPlaylist(String playlistName, int songID) {

        //Vibrate device
        Utils.vibrate(getApplicationContext());

        //get all playlists
        Cursor playListCursor = AppController.getGlobalContentResolvere().query(
                MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, new String[]{"*"}, null, null,
                null);

        long playlistId = 0;

        playListCursor.moveToFirst();

        do {

            //check if selected playlsit already exist
            if (playListCursor.getString(playListCursor
                    .getColumnIndex(MediaStore.Audio.Playlists.NAME)).
                    equalsIgnoreCase(playlistName)) {

                playlistId = playListCursor.getLong(playListCursor
                        .getColumnIndex(MediaStore.Audio.Playlists._ID));
                break;
            }
        } while (playListCursor.moveToNext());

        //Playlist  doesnt exist creating new with given name
        if (playlistId == 0) {

            Log.d(TAG, "CREATING PLAYLIST: " + playlistName);

            ContentValues playlisrContentValue = new ContentValues();

            //Add name
            playlisrContentValue.put(MediaStore.Audio.Playlists.NAME, playlistName);

            //update modified value
            playlisrContentValue.put(MediaStore.Audio.Playlists.DATE_MODIFIED,
                    System.currentTimeMillis());

            Uri playlistURl = AppController.getGlobalContentResolvere().insert(
                    MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, playlisrContentValue);

            Log.d(TAG, "Added PlayLIst: " + playlistURl);

        } else {

            //Playlist alreay exist add to playlist
            String[] cols = new String[]{
                    "count(*)"
            };

            Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);

            Cursor favListCursor = AppController.getGlobalContentResolvere().query(uri, cols, null, null, null);

            favListCursor.moveToFirst();

            final int base = favListCursor.getInt(0);

            //playlist updated delete older playlist art so that we can create new
            Toast.makeText(AudioPlayerActivity.this, "deleted old file" + new File(AppContants.PLAY_LIST_DIR + playlistId + ".png").delete(), Toast.LENGTH_SHORT).show();

            favListCursor.close();

            //add song to last
            ContentValues values = new ContentValues();

            values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, base + songID);

            values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songID);

            AppController.getGlobalContentResolvere().insert(uri, values);


            //Debug purpose
            Toast.makeText(AudioPlayerActivity.this, "Added to Favourite list " +
                            CenterRepository.getInstance().getAudioCollection().getSongAt(AppConfig.SONG_NUMBER).getTitle()
                    , Toast.LENGTH_SHORT).show();

        }
    }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154