Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the first and last name of a google account that i'm logged in, in Android?

I have a simple application with google authentification, and I want to display a welcome message. If the email account is j[email protected], I want a Toast with "Welcome John Smith!" How can I do that?

This is my code:

if (user == null) {
        startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE);
    } else {
        Toast.makeText(MainActivity.this, "Welcome " + userName, Toast.LENGTH_SHORT).show();
    }

I tried to use this code, but I get only the user name, not the first and last name.

AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();

Thanks in advance!

like image 332
Alex Mamo Avatar asked Dec 26 '16 11:12

Alex Mamo


1 Answers

onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent result) {
    if (requestCode == GOOGLE_REQUEST_CODE) { // Google + callback
       handleSignInResult(Auth.GoogleSignInApi.getSignInResultFromIntent(result));
       }
}

handleSignInResult :

private void handleSignInResult(GoogleSignInResult googleSignInResult) {
    if (googleSignInResult.isSuccess()) {
        GoogleSignInAccount acct = googleSignInResult.getSignInAccount();
        if (acct != null) {
            //get the data you need from GoogleSignInAccount
            }
        } else {
            Toast.makeText(context.getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
        }
    }

You can find more on GoogleSignInAccount : https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount

like image 116
Ahmed Abidi Avatar answered Oct 20 '22 00:10

Ahmed Abidi