Q:

AccountManager fails to add account on Sony XZ 7.1.1

The app I'm currently developing has recently been showing problems when users update to 7.1.1 om Sony mobiles
On a Sony XZ we can see this in the log when trying to addAccountExplicitly:
AccountManagerService( 1503): insertAccountIntoDatabase: Account {name=something@something.com, type=com.myapplication.go}, skipping since the account already exists
The application was installed and the account was added by our app prior to upgrade. It seems as if the account has not been completely removed/readded.
How can we in our app recover from this?
Why is this happening?
I have read of similar problems in Nougat preview but we can not recover from it with removeAccountExplicitly and then add it again as suggested in link below. The result is the same as above and uninstallation of the app does not clear the account and neither does a phone restart.
AccountManager does not add custom account in Android N preview

A:

We found a possible cause and solution for the problem.
Symptoms
TL;DR It's Sony's fault.
From our user base, it looked like only Sony XZ users who used our app prior to upgrading their device to 7.1.1.
We went as far as buying several Sony XZ devices (and eventually returning them back to the shop), upgrading them from Android 6.0 to 7.1.1 and trying to reproduce the issue. But with no luck.
However, we found another way to achieve the same "symptoms" using the Android emulator. The steps are:

Launch emulator
Login into your app (so that user is added to AccountManager)
Go to the terminal, and do the following

Steps:
adb shell
su
cd /data/system_de/0/
rm accounts_de.db

Restart your emulator
From now on your issue is reproducible.

Moreover, if you'll check /data/system_ce/0/accounts_ce.db you will see that this is a database which still contains your previous user. That is most likely why AccountManager does not allow you to insert same user again.
It looks like that during update to Android 7.1.1, Sony somehow corrupted accounts_de.db which contained the original account.
Solution
Since account with the same name is already in the database (and you can't really remove it from there), we basically can't insert user with the same username again. However, we can insert account with slightly updated username:
if (!accountManager.addAccountExplicitly(account, password, bundle)) {
    // We failed to add the account. Fallback to workaround.
    accountManager.addAccountExplicitly(
        new Account(username + "\n", accountType), // this line solves the issue
        password,
        bundle
    );
}

Since this account is now different from original account (thanks to \n character), it can be inserted into AccountManager database.

