Why the ACTION_CREATE_DOCUMENT intent doesn't rename the file correctly if it exists?

Viewed 1187

Hy,

I use ACTION_CREATE_DOCUMENT intent in my application, to let the users to choice the path of downloaded file. It works fine, when the file name is unique.

According to documentation, if the file name is exists, the system doesn't overwrite the original file, instead of that, the system appends the number to the end of the file.

I tried the original android example, and first, when there is no other file with the same name, the file is created perfectly, and I can open, but when I would like to save the file in the same name, athought the system appends the number, not before extension , but after the extension something like this: fileName.jpg(1), and after that I can not open, until then I delete this appended string.

I tried only my Samssung Galaxy S20 with Android 10, it is a specific issue, or did I something wrong?

Maybe it will be a good solution, if I could check the file name, before the save, but the document tree creates the file.

I tried this code, from the documentation:

const val CREATE_FILE = 1

private fun createFile() {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "application/pdf"
        putExtra(Intent.EXTRA_TITLE, "invoice.pdf")

    }
    startActivityForResult(intent, CREATE_FILE)
}

Thanks for the help.

2 Answers

If there is no extension (given by the MIME type) after the file name, android will automatically add it. That is fine.

Now it will find out if a file with this name exists and if so, it will add (1) after the part written by user.

These examples show how the file name evolved:

    "invoice.pdf" -> "invoice.pdf" -> "invoice.pdf (1)"
    "invoice" -> "invoice.pdf" -> "invoice (1).pdf"

So just don't put the extension in EXTRA_TITLE:

const val CREATE_FILE = 1

private fun createFile() {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "application/pdf"
        putExtra(Intent.EXTRA_TITLE, "invoice")

    }
    startActivityForResult(intent, CREATE_FILE)
}

It is much better to use ACTION_OPEN_DOCUMENT_TREE to let the user pick a directory.

After that you can decide if the user determines the name of a new file or that your app does it.

Anyhow you can now check if a file name is already in use by for instance listing the contents of the directory. Or on another way.

If the file already exists then obtain the uri for that file and use it to overwrite the content.

Related