I can't delete the folder's content from path

52 Views Asked by At

I'm currently getting this path from my FileExplorer

val path = "content://com.android.externalstorage.documents/tree/primary:Download"

And I'm trying to delete the content of this location:

     val fileFolder = File(path)
     deleteFolderContent(fileFolder)

     private fun deleteFolderContent(fileFolder: File) {
        val files = fileFolder.listFiles()
        if (files.isNullOrEmpty()) {
            return
        } else {
            for (file in files) {
                file.delete()
            }
        }
    }

But files is always null and I can't delete the content. What am I doing wrong? Can anyone help me? Thanks.

Update:

For obtain this "path" I did this:

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, SELECT_FOLDER_REQUEST_CODE)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == SELECT_FOLDER_REQUEST_CODE && resultCode == RESULT_OK) {
        val uriTree = data?.data 
     }
}
1

There are 1 best solutions below

0
On

you can't access content directory as a File (even when URI points on local storage). check out Providers and ContentResolver, HERE you have some basics, for files there is special one: FileProvider. but for your case ContentResolver may fit for your needs best, with method:

context.contentResolver.delete(uriToDelete, null, null)