我正在查询所有音乐文件的MediaStore.Audio.Media.EXTERNAL_CONTENT_URI。它工作正常,但每当我想从我的sdCard删除音乐文件时,列表将不会更新。知道如何更新列表吗?
这是获取音乐文件的代码:
Cursor cursor;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
cursor = getActivity().getContentResolver().query(uri, {"*"}, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String songName = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String path = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
String albumName = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
int albumId = cursor
.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
songs.add(new SongItem(albumName, albumId, path, songname));
} while (cursor.moveToNext());
}
}
答案 0 :(得分:0)
新添加的文件将添加到光标中,并且实际上不会删除已删除的文件。
为此,我们需要检查文件是否可用。如果不可用,请使用内容提供商从数据库中删除
这是我解决问题的方法:
Uri files= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor= managedQuery(files, STAR, null,null,null);
cursor.moveToFirst();
for(int r= 0; r<cursor.getCount(); r++, cursor.moveToNext()){
int i = cursor.getInt(0);
File file = new File(cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)));
if(file.exists()){
// keep files if it is empty
list.add("Keeping : " + cursor.getString(2) + " : id(" + i + ")");
}else{
// delete any play-lists with a data length of '0'
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, i);
getContentResolver().delete(uri, null, null);
list.add("Deleted : " + cursor.getString(2) + " : id(" + i + ")");
}
}
cursor.close();