How to get the first and last name of the google account I am registered with on Android?

I have a simple google authentication app and I want to show a welcome message. If the email account is j ohnsmith@gmail.com , I want Toast with "welcome John Smith!" . How can i do this?

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 only get the username and not the first and last name.

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

Thanks in advance!

+5
source share
2 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 at GoogleSignInAccount : https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount

+2
source

Well edited answer -

 Cursor c = activity.getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null); int count = c.getCount(); String[] columnNames = c.getColumnNames(); boolean b = c.moveToFirst(); int position = c.getPosition(); if (count == 1 && position == 0) { for (int j = 0; j < columnNames.length; j++) { String columnName = columnNames[j]; String columnValue = c.getString(c.getColumnIndex(columnName))); ... //Use the values } } c.close(); 

j = 0 represents DISPLAY_NAME.

But this is only available for ICS. Add the READ_PROFILE and READ_CONTACTS permissions to your AndroidManifest.

0
source

Source: https://habr.com/ru/post/1261903/


All Articles