Search code examples
androidandroid-permissionsgoogle-authenticationgoogle-oauthgoogle-account

GoogleAccountCredential setSelectedAccountName but still null


The account name is null even after being set.

I've seen this answer, but I do have the GET_ACCOUNTS permission in both the manifest and secured at runtime.

The following setup is being run on a Pixel XL emulator API 25 (Android 7.1.1).

Manifest

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Activity

private void queryAPI() {
    if (mCredential.getSelectedAccountName() == null) {
        if (checkSelfPermission(Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[] {Manifest.permission.GET_ACCOUNTS}, RCP_AUTH_CRED);
            return;
        }

        mCredential.setSelectedAccountName("[email protected]");
        Log.d(TAG, "queryAPI: account name " + mCredential.getSelectedAccountName());
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case RCP_AUTH_CRED:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                queryAPI();
            } else {
                Log.d(TAG, "onRequestPermissionsResult: " + Integer.toString(grantResults[0]));
            }
            break;
    }
}

Logcat

04-18 21:26:47.590 2700-2700/com.package D/MainActivity: queryAPI: account name null

Solution

  • Is this google account "[email protected]" setup in accounts on the device?

    First you need to setup the google account that you want to use it in your app by going to settings / accounts / add account on the device where you are testing it. Just passing account name is not enough, the account must exist on the device.

    If google account is required in order for users to use your app, you can just force users to create google account by directing users to account selection screen by firing an intent using newChooseAccountIntent() method.