0

I would appreciate some help in a problem. I'm trying to add songs to a playlist, but whenever I try to use either insert or bulkInsert, it does not work, if I use insert I'll just get a null row as a return value, if I use bulkInsert it will throw a NullPointerException, ( so that basically means that no rows have been inserted, because bulkInsert returns the number of inserted rows ) Below I have the code I used, and a snap of the state of my method when I was debugging it:

 public void savePlaylist(Playlist p) {

    String name = p.getPlaylistName();
    Uri playlistURI = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
    ContentResolver contentResolver = context.getContentResolver();
    Cursor playlistCursor = contentResolver.query(playlistURI, new String[]{"*"}, null, null, null);
    long playlistID = getPlaylistID(playlistCursor, name);


    if (playlistID == 0)

    {
        ContentValues playlistValue = new ContentValues();
        playlistValue.put(MediaStore.Audio.Playlists.NAME, name);
        playlistValue.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis());
        contentResolver.insert(playlistURI, playlistValue);
        playlistID = getPlaylistID(contentResolver.query(playlistURI, new String[]{"*"}, null, null, null), name);
    }

    Uri insertionUri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistID);

    ContentValues[] rowsToAdd = new ContentValues[p.getSongs().size()];

    for (int i = 0; i < p.getSongs().size(); i++) {
        Song toAdd = p.getSongs().get(i);
        rowsToAdd[i] = new ContentValues();
        rowsToAdd[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, toAdd.getId());

    }

     try {
        int result = context.getContentResolver().bulkInsert(insertionUri, rowsToAdd);

        if (result > 0) {
            Log.d("DEBUG", "Row inserted succesfully");
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

I should specify, this method is used to Add a playlist if it does not exist, and add songs to it if it does, before I start handling events like if songs already exist or not, I should fix this problem first.

Snap from when debugging, up to the point I am calling bulkInsert

Community
  • 1
  • 1
Matthew
  • 105
  • 1
  • 11
  • I have previously posted on creating playlists https://stackoverflow.com/questions/34883564/querying-playlist-from-mediastore/34909106#34909106 – Theo Oct 14 '17 at 14:48
  • Hei thank you for answering, the difference ( apart that I use bulkInsert ) from your code and mine is that I don't put PLAYLIST_ID and AUDIO_ORDER values into the row that I want to insert, the rest is pretty much the same, do you think that the fact that I only insert the AUDIO_ID would make it blow ? – Matthew Oct 16 '17 at 16:28
  • You need the playlist_id otherwise the track does not know which playlist it is on. Without it it makes no sense. – Theo Oct 17 '17 at 17:14

0 Answers0