Skip to content Skip to sidebar Skip to footer

Delete File Using Uri

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

Solution 1:

You should try this:

Filefile=newFile(selectedFilePath);
booleandeleted= file.delete();

where selectedFilePath is the path of the file you want to delete - for example:

/sdcard/YourCustomDirectory/ExampleFile.mp3

Solution 2:

Kotlin extension :

fun File.delete(context: Context): Boolean {
   var selectionArgs = arrayOf(this.absolutePath)
   val contentResolver = context.getContentResolver()
   varwhere: String? = nullvar filesUri: Uri? = nullif (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)

Solution 3:

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

Post a Comment for "Delete File Using Uri"