4

I try to delete file in this way:

getContentResolver().delete(uri, null, null)

it works for videos when uri is content://media/external/video/media/1214 but doesn't work for audio files content://media/external/audio/media/1212.

I need that to delete files that I receive from camera and voice recorder because currently those files are in my app dir and on sd card.

Can somebody help me? What's wrong?

Giks91
  • 273
  • 3
  • 5
  • 20
  • File file=new File(yourUri); file.delete(); – ak sacha Jan 18 '17 at 11:08
  • Thanks in advance posts will not receive help. – greenapps Jan 18 '17 at 11:44
  • 2
    Are you getting any errors/exceptions when you try to delete? Could the file be in use? – TripeHound Jan 18 '17 at 13:05
  • For some reason it also happened to me. I could delete the picture I created in the external directory, but trying to delete a voice file I created caused an exception. So, using the answer below, I could delete it. `File(uri.path).delete()`. I could not use `File(uri)`, because File was expecting a Java URI and my uri was an Android Uri. – Damn Vegetables Aug 08 '18 at 10:04

2 Answers2

7

Kotlin extension :

fun File.delete(context: Context): Boolean {
   var selectionArgs = arrayOf(this.absolutePath)
   val contentResolver = context.getContentResolver()
   var where: String? = null
   var filesUri: Uri? = null
   if (android.os.Build.VERSION.SDK_INT >= 29) {
      filesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
      where = MediaStore.Images.Media._ID + "=?"
      selectionArgs = arrayOf(this.name)
   } else {
      where = MediaStore.MediaColumns.DATA + "=?"
      filesUri = MediaStore.Files.getContentUri("external")
   }

   val int = contentResolver.delete(filesUri!!, where, selectionArgs)

   return !this.exists()
}

Call like this:

val file = File(uri.path)
file.delete(applicationContext)
Kasım Özdemir
  • 5,414
  • 3
  • 18
  • 35
0

Below code not only deletes the image file but also deletes the 0Byte file that gets left behind when image is deleted. I observed this 0Byte ghost file behavior in Android 10.

    val fileToDelete = File(photoUri.path)
    if (fileToDelete.exists()) {
        if (fileToDelete.delete()) {
            if (fileToDelete.exists()) {
                fileToDelete.canonicalFile.delete()
                if (fileToDelete.exists()) {
                    getApplicationContext().deleteFile(fileToDelete.name)
                }
            }
            Log.e("", "File Deleted " + savedPhotoUri.path)
        } else {
            Log.e("", "File not Deleted " + savedPhotoUri.path)
        }
    }
Ramakrishna Joshi
  • 1,442
  • 17
  • 22