Home > Back-end >  Weird create file issue
Weird create file issue

Time:12-13

Android 11.

android:requestLegacyExternalStorage is set to true.

My app can create a file and write to it. It can then delete the file and create it again.

The weird issue is that in case the user deletes the file (e.g. by using the Files app), then my app can't create this file anymore. Android returns "file already exists" error.

What are the reasons of such a behavior and are there any workarounds? I'm working with files using native C /Qt code.

The code I'm using to create a file:

bool isOk = QFile(path).open(QFile::WriteOnly);

This code works fine in case the file specified in path variable was never deleted by the user.

Here another developer (VaranasiPrasanth-3918) reports about the same behavior.

CodePudding user response:

It seems this all is caused by Android internals I don't care about now.

I've found workaround which explains it. It seems it just Android's bug. It seems the goal of this is to prevent apps from creating files under names previously used by another apps. And this mechanism just does not take the case described in this question into account.

The workaround is to create file under different name and then to just rename it to the desired name. Note, that this workaround does NOT work in case a file was originally created by another app.

So, here is an example:

if (error)
{
    // Weird Android issue: in case a file was deleted by an external app (e.g. file manager),
    // it can't be created again.
    // But there is a workaround: it's possible to create a file under a different name and then rename it to the desired name.
    
    if (!QFile(name).exists())
    {
        auto waPath = filePathPart(name);
        if (!waPath.isEmpty())
            waPath  = '/';
        waPath  = QUuid::createUuid().toString(QUuid::WithoutBraces);
        if (QFile(waPath).open(QFile::WriteOnly))
        {
            if (QFile::rename(waPath, name))
            {
                waPath = name;

                if (QFile(name).open(QFile::WriteOnly))
                    error.clear();
            }
            if (error)
                QFile::remove(waPath);
        }
    }
}

CodePudding user response:

Your problem is most probably caused by a still existing entry for your file in the MediaStore.

The file should not only be deleted but also this entry.

So check existence and delete entry. Or yet better: delete the file using the MediaStore.

  • Related