In my Music-Player, a Playlist may contain two identical songs (the user adds the same song two times).
Let's say the song which is 2 times in the Playlist has the id 7664.
When removing this song from the Playlist, ContentResolver.delete(URI_OF_PLAYLIST, "audio_id=7664", null);
removes both matches.
So how do I only delete one match?
Thanks in advance!
This is how I do it in my app New Playlist Manager:
step 1: create an array with audio Ids
step 2: whilst looping around this, use the .lastindex() function to determine if it exists elsewhere. (otherwise the value should be the same as position)
step 3: if found, remove from audio Ids array by setting it to null (you do not want to change its size) and remove from playlist
step 4: reorder the playorder
public void dedupe_playlist(Context context, long playlist_id) {
Cursor cursor = plist.getPlaylistTracks(context, playlist_id);
ArrayList<String> audio_ids = new ArrayList<>();
// build up the array with audio_id's
int i = 0;
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String audio_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID));
audio_ids.add(audio_id);
}
i = 0;
int duplicates = i;
boolean success = false;
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String audio_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID));
duplicates = audio_ids.lastIndexOf(audio_id);
if (duplicates > i) {
success = true;
cursor.moveToPosition(duplicates);
int _id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members._ID));
removePlaylistTrack(context, playlist_id, _id);
audio_ids.set(duplicates, null);
cursor.moveToPosition(i - 1); // move back to test again
} else {
i++;
}
}
if (success) {
renumber_playorder(context, playlist_id);
}
try {
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removePlaylistTrack(Context context, long selectedplaylist,
int _id) {
ContentResolver resolver = context.getContentResolver();
Uri newuri = MediaStore.Audio.Playlists.Members.getContentUri(
"external", selectedplaylist);
try {
resolver.delete(newuri, MediaStore.Audio.Playlists.Members._ID + " = " + _id, null);
} catch (Exception e) {
e.printStackTrace();
}
}