在我的音乐播放器中,播放列表可能包含两首相同的歌曲(用户添加了两次相同的歌曲)。假设播放列表中出现 2 次的歌曲的 id 为 7664。从播放列表中删除这首歌时,ContentResolver.delete(URI_OF_PLAYLIST, "audio_id=7664", null);
会删除两个匹配项。那么如何只删除一场比赛呢?
提前致谢!
在我的音乐播放器中,播放列表可能包含两首相同的歌曲(用户添加了两次相同的歌曲)。假设播放列表中出现 2 次的歌曲的 id 为 7664。从播放列表中删除这首歌时,ContentResolver.delete(URI_OF_PLAYLIST, "audio_id=7664", null);
会删除两个匹配项。那么如何只删除一场比赛呢?
提前致谢!
这就是我在我的应用新播放列表管理器中的操作方式:
第 1 步:创建一个带有音频 ID 的数组
第 2 步:在循环时,使用 .lastindex() 函数来确定它是否存在于其他地方。(否则该值应与位置相同)
第 3 步:如果找到,则通过将其设置为 null(您不想更改其大小)从音频 Ids 数组中删除并从播放列表中删除
第 4 步:重新排序播放顺序
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();
}
}
要重新排序播放列表:
public void renumber_playorder(Context context, long playlist_id) {
Cursor cursor = getPlaylistTracks(context, playlist_id);
Uri newuri = MediaStore.Audio.Playlists.Members.getContentUri(
"external", playlist_id);
ContentResolver resolver = context.getContentResolver();
ContentValues values = new ContentValues();
int i = 0;
if (cursor != null && cursor.moveToFirst()) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String _id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.Members._ID));
String[] selection = {_id};
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i);
resolver.update(newuri, values, MediaStore.Audio.Playlists.Members._ID + " =? ", selection);
i++;
}
cursor.close();
}
}