0

I wish delete music file stored on my phone (has no SD card) in Music folder. I have file path and File.exists() said true. Next, File.delete() also said true, but file stay in its place. But! After "deletion" I can no longer play this file, edit name and also can't copy it. But I can delete it manually.

I've set android.permission.WRITE_EXTERNAL_STORAGE. OS 4.4.4 GPE

Where is my mistake? Any suggestions, thanks.

    File file = new File(Path);
    if (file.exists()){
        file.setWritable(true, false);
        return file.delete();
    }
Konstantin Konopko
  • 5,229
  • 4
  • 36
  • 62

2 Answers2

1

Windows is not looking at external storage directly. It is looking at the data served up by the Media Transfer Protocol (MTP) server on your Android device. It, in turn, is working with the MediaStore index, not the actual filesystem.

If you make any change to external storage, such as deleting a file, you need to update MediaStore. Off the cuff, I do not recall exactly how to do that for a deleted file, though I would consider trying to use MediaScannerConnection and scanFile() to perhaps scan the directory that contained the deleted file.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks, I used `context.getContentResolver().delete()` and it's seems to work. But then I trying get free space value using `StatFs` and it's not changed, stay the same. May be you know how to update it? – Konstantin Konopko Oct 22 '14 at 23:45
  • @konopko: I would expect the disk space to increase when you actually delete the file. I don't quite know what you used with the `ContentResolver`, but that may have just deleted the `MediaStore` entry, not the file. If so, not only would you not recover the disk space, but the file will show back up in `MediaStore` when it makes its periodic scan of all of external storage. – CommonsWare Oct 22 '14 at 23:49
0

So, my final solution that seems to work is:

public Boolean deleteTrack(String key){
    MusicTrack track = getAlbum(0).getTrackByKey(key);
    if (track == null) return false;

    File file = new File(track.getData().Path);
    if (file.exists()){
        file.setWritable(true, false);
        String where = MediaStore.Audio.Media.DATA +"=\""+ track.getData().Path +"\"";
        if (context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null) == 1){
            if (file.exists()){
                Boolean d = file.delete();
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                return d;
            }
            return true;
        }
    }
    return false;
}
Konstantin Konopko
  • 5,229
  • 4
  • 36
  • 62