Audio.Media.EXTERNAL_CONTENT_URI list is not updated after file deletion

I am asking for MediaStore.Audio.Media.EXTERNAL_CONTENT_URI for all music files. It works fine, but whenever I want to delete a music file from my SDCard, the list will not update. Any idea how to update the list?

here's my code for getting music files:

    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());
        }
    }

      

+3


source to share


1 answer


The added files are added to the cursor and the deleted file will not be deleted.

To do this, we need to check if the file is available or not. If this is not possible, remove it from the database using the content provider



This is how I fixed my problem:

        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();

      

0


source







All Articles