-->

AccountManager IllegalArgumentException: key is nu

2019-09-02 20:37发布

问题:

Ok, I'm getting an IllegalArgumentException at a point where it shouldn't.

I have a custom extension of Account that is saved using the AccountManager:

// Method inside a custom extension of Account
public boolean save(AccountManager manager) {
    removeAll(manager);
    boolean result = manager.addAccountExplicitly(this, null, toBundle());
    manager.setUserData(this, KEY_1, value1);
    manager.setUserData(this, KEY_2, value2);
    manager.setUserData(this, KEY_3, value3);
    return result;
}

The keys are constant String values but app still throws:

java.lang.IllegalArgumentException: key is null

I have to say that I'm only attaching the user data in this fashion because using:

 manager.addAccountExplicitly(this, null, toBundle());

didn't seem to attach the values. Do the keys require a special name pattern?

Anybody had this problem before?


Update:

It gets thrown inside the manager.setUserData() which looks like this (Android code):

public void setUserData(final Account account, final String key, final String value) {
    if (account == null) throw new IllegalArgumentException("account is null");
    if (key == null) throw new IllegalArgumentException("key is null");
    try {
        mService.setUserData(account, key, value);
    } catch (RemoteException e) {
        // won't ever happen
        throw new RuntimeException(e);
    }
}

When I "walk" into this method with eclipse I get this in the debug perspective:

The values aren't null >o<

回答1:

Ok, after further research into android's AccountManager I did not find a way to make it work like I was trying but I found a solution.

Instead of saving the details as an user data bundle I save them as authToken values using the key as the authTokenType like this:

public boolean save(AccountManager manager) {
    removeAll(manager);
    boolean result = manager.addAccountExplicitly(this, null, toBundle());
    manager.setAuthToken(this, KEY_1, value1);
    manager.setAuthToken(this, KEY_2, value2);
    manager.setAuthToken(this, KEY_3, value3);
    return result;
}

And then retrieving the values like this:

value1 = manager.peekAuthToken(account, KEY_1);

I'm still not sure if this is the way to store data for an Account but it's the only one I've managed to make work so far.