How to Resolve SIGN_IN_REQUIRED error in google plus integration? - android

I have an app in which i have implemented google+ sign in. I have checked all the code and found after dubugging it is always throws an error in onConnectionFailed(ConnectionResult result) where result is shown as follow:
ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{425b8550: android.os.BinderProxy#423ec2e8}, message=null}
code:-
mGoogleApiClient = buildGoogleAPIClient();
gPlusLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
processGPlusSignIn();
}
});
private void processGPlusSignIn() {
if (!mGoogleApiClient.isConnecting()) {
Log.e("", "GPLUS area 111");
startExecutingGPlusLoginProcess();
mSignInClicked = true;
}
}
private void startExecutingGPlusLoginProcess() {
if (mConnectionResult != null && mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
Log.i("Registration", "Starting...");
mConnectionResult.startResolutionForResult(this, GPLUS_SIGN_IN_REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
Log.e("Registartion", "Exception***" + e);
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG,"onConnectionFailed called");
if (!connectionResult.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, ERROR_DIALOG_REQUEST_CODE).show();
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult;
Log.e("Registration", "Result?***" + connectionResult);
if (mSignInClicked) {
startExecutingGPlusLoginProcess();
}
}
}

You may try the below code :
first you need to initalize GoogleApi like that:
private void googleInitialization() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mGoogleApiClient.connect();
}
After that you need to call this method like that:-
googleInitialization();
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
and thid handle in OnActivityResult there is a CallBackManager which is very useful to call the login button
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
Now, Get result in the below method:
private void handleSignInResult(GoogleSignInResult result) {
Log.d("handleSignInResult", "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String email = acct.getEmail();
if (personName.contains(" ")) {
String fname = personName.substring(0, personName.lastIndexOf(" ") + 1);
String lname = personName.substring(personName.lastIndexOf(" ") + 1);
Log.e("First name", fname);
Log.e("Last name", lname);
} else
String fname = personName;
Log.e("Profile Info", "Name: " + personName + ", email: " + email);
}
}

Related

Google Sign in with android Studio

I am doing sign in with Google account I have followed for creating a JSON file. Also I have integrate JSON file with my project.But I am getting exception that account.getDisplayName throws nullPointException.
Google sign in code:
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
private SignInButton signInButton;
private GoogleApiClient client;
private static final int REQ_CODE = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = (SignInButton)findViewById(R.id.btn_signin);
GoogleSignInOptions options = new
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestProfile()
.requestEmail()
.build();
client = new GoogleApiClient.Builder(this).
enableAutoManage(this,this).
addApi(Auth.GOOGLE_SIGN_IN_API,options).build();
signInButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_signin:
signIn();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void signIn(){
Intent intent = Auth.GoogleSignInApi.getSignInIntent(client);
startActivityForResult(intent,REQ_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE){
GoogleSignInResult result =
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
}
private void handleResult(GoogleSignInResult result) {
if (result.isSuccess()){
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String image = account.getPhotoUrl().toString();
}
}
}
and here is my compiled library:
implementation 'com.google.android.gms:play-services-auth:16.0.1'
please guide where I am doing mistake
Try this :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == REQ_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
// G+
Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
System.out.println("Display Name: " + person.getDisplayName());
System.out.println("Gender: " + person.getGender());
System.out.println("AboutMe: " + person.getAboutMe());
System.out.println("Birthday: " + person.getBirthday());
System.out.println("Current Location: " + person.getCurrentLocation());
System.out.println("Language: " + person.getLanguage());
}
}
If you want " UserName, Email Id, Profile URL, Google Id" of google.
You have done mistake with "GoogleSignInOptions". Please Replace my GoogleSignInOptions with your GoogleSignInOptions code to resolve your problem.
Then, Your Solution is here -> You should follow below code.
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 9001;
private LinearLayout googleBtn;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
googleBtn = view.findViewById(R.id.googleBtn);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.default_web_client_id))
.build();
mGoogleApiClient = new GoogleApiClient.Builder(Objects.requireNonNull(getActivity()))
.enableAutoManage(getActivity(), 0, connectionResult -> {
Snackbar.make(googleBtn, "Connection failed..", Snackbar.LENGTH_SHORT).show();
Log.e(TAG, "Google connection Error: " + connectionResult.getErrorMessage());
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(#Nullable Bundle bundle) {
//Log.e(TAG,"mGoogleApiClient is connected");
mGoogleApiClient.clearDefaultAccountAndReconnect();
}
#Override
public void onConnectionSuspended(int i) {
}
})
.build();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.googleBtn:
//stopAutoManage first otherwise throws exception Already managing a GoogleApiClient with id 0
if (mGoogleApiClient != null) {
mGoogleApiClient.stopAutoManage(Objects.requireNonNull(getActivity()));
}
loginWithGoogle();
break;
}
public void loginWithGoogle() {
Log.e(TAG, "is connected? " + mGoogleApiClient.isConnected());
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
Objects.requireNonNull(getActivity()).startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
public void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
// Get account information
if (acct != null) {
Name = acct.getDisplayName();
if (acct.getEmail() != null) {
Email = acct.getEmail();
} else {
Email = "";
}
SocialUserId = acct.getId();
Gender = "";
String idToken = acct.getIdToken();
String profileURL = Objects.requireNonNull(acct.getPhotoUrl()).toString();
String status = "Status: \nFullname: " + Name + "\n Email: " + Email + "\nProfile URI: " + profileURL;
Log.i(TAG, "Google signin " + status);
Log.i(TAG, "ID Token: " + idToken);
Log.i(TAG, "ID: " + acct.getId());
//TODO Temporary "acct.getCompId()" pass "idToken"
checkIsUserExists();
}
} else {
hideProgressBar();
Log.e(TAG, "Failed!! Google Result " + result.getStatus());
int status_code = result.getStatus().getStatusCode();
switch (status_code) {
case GoogleSignInStatusCodes.SIGN_IN_CANCELLED:
Snackbar.make(googleBtn, "Google sign in has been cancelled.", Snackbar.LENGTH_SHORT).show();
break;
case GoogleSignInStatusCodes.NETWORK_ERROR:
Snackbar.make(googleBtn, "Application is unable to connect with internet", Snackbar.LENGTH_SHORT).show();
default:
//AppUtils.showSnackBar(LandingActivity.this, btnLogin, GoogleSignInStatusCodes.getStatusCodeString(result.getStatus().getStatusCode()), R.integer.snackbar_duration_3sec);
break;
}
}
}
You can follow these steps to integrate Google Sign In in your Android application
Step 1. Implement library
implementation 'com.google.android.gms:play-services-auth:17.0.0'
Step 2. Add google login button
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
Step 3. Add below code in your activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (SignInButton)findViewById(R.id.signup);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, google_login);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("called", "called");
if (requestCode == google_login) {
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Disaplay data on your screen
Log.e("email", account.getEmail());
Log.e("name", account.getDisplayName());
Log.e("id", account.getId());
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.e("signInResult", ":failed code=" + e.getStatusCode());
}
}
You can follow this tutorial for complete implementation :- Sign In with Google in your Android Application

Google sign in - GoogleSignInAccount returns null

Im trying to integrate a google sign in my app but it keeps failing and GoogleSignInAccount returns a null object and it displays cancelled. I dont know whats going wrong. Is it this or the dependencies? This is my code in onCreate
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestProfile()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
final SignInButton googleLoginButton = (SignInButton) findViewById(R.id.googleLoginButton);
googleLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
googleSignIn();
}
});
And these are the other functions
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// do nothing
}
private void googleSignIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
} else {
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
}
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
if (acct != null) {
Toast.makeText(MainActivity.this, "Welcome " + acct.getDisplayName(),
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Cancelled!",
Toast.LENGTH_SHORT).show();
}
}

How to Signout GoogleApiClint from another Activity or Fragment android

i am using Google Api Clint for login with google account. my code is working fine, but when i am trying to sign out from a fragment Logout.java, its not working please see my login Activity code below.
in oncreate
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
And rest of the Code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e(TAG, "display name: " + acct.getDisplayName());
String personName;
//String personPhotoUrl = acct.getPhotoUrl().toString();
String email;
String gid;
String location = "Location Not Set";
String oarth = "Google";
String gender = "Not Set";
if(acct.getDisplayName() != null){
personName = acct.getDisplayName();
}else{
personName ="";
}
if(acct.getEmail() != null){
email = acct.getEmail();
}else{
email ="";
}
if(acct.getId() != null){
gid = String.valueOf(acct.getId());
}else{
gid ="";
}
Log.e(TAG, "Name: " + personName + ", email: " + email
+ ", id: " + gid +", location:" +location+", oarth: "+oarth+", gender: "+gender);
//session.setMember(gid, personName, location, gender, email, oarth);
InsertFbLogindata(gid, personName, location, gender, email, oarth);
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
case R.id.btn_sign_out:
signOut();
break;
case R.id.btn_revoke_access:
revokeAccess();
break;
}
}
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
}
}
in my logout Fragment
public class logout extends Fragment {
Button Logout;
Session session;
LoginActivity la;
private GoogleApiClient mGoogleApiClient;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.sent_layout,container,false);
final Button logout = (Button)root.findViewById(R.id.buttonLogout);
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
session = new Session(getActivity());
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
session.setLogin(false);
LoginManager.getInstance().logOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
return root;
}
}
i tried so many examples but no use. is there any possible to this. please suggest the best way.
your activity code is absolutely fine but in login.java, you have to change some code as follows.
get instance of googlesigninoptions
firebase authentication
that's it you can call `mAuth.signout()
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient=GoogleSignIn.getClient(
getActivity(),gso);
mAuth=FirebaseAuth.getInstance();
mGoogleSignInClient.signOut().
addOnCompleteListener(getActivity(),
new OnCompleteListener<Void>()
{
#Override
public void onComplete (#NonNull Task < Void > task) {
SharedPreferences getUser = getActivity().getSharedPreferences("user_info", getActivity().MODE_PRIVATE);
SharedPreferences.Editor ed = getUser.edit();
ed.putString("username", null);
ed.commit();
Snackbar.make(v.getRootView().findViewById(R.id.settings_fragment_layout), "Logged Out Successfully", Snackbar.LENGTH_SHORT).show();
HomeFragment hf = new HomeFragment();
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, hf)
.commit();
}
});

android google plus login

I can get all data when user is signed in but when user enter his credential through my app like email id and password then it gives null value to name,first name and last name but only I can get is user id and email id.
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestProfile()
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
handleSignInResult(googleSignInResult);
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
if(status==1) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount acct = result.getSignInAccount();
id=acct.getId();
googleId=id;
personPhotoUrl = acct.getPhotoUrl();
if(acct.getPhotoUrl() != null) {
imageUrl = acct.getPhotoUrl().toString();
}
else {
imageUrl="https://www.tineye.com/query/2abdd40717c034bf2dbcd6a0253b933d2a655920?size=160";
}
email = acct.getEmail();
name = acct.getDisplayName();
firstName = acct.getGivenName();
lastName = acct.getFamilyName();
details=new Details(name, firstName, lastName,email, birthday,imageUrl);
new GetDetails().execute();
if(details==null)
{
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("googleId", googleId);
startActivity(intent);
finish();
}
} else {
}
}

Unable to signup in Google plus Android in release apk

I am unable to signup in google plus in my android application. It is working fine in jelly bean and kitkat. It is not working in lollypop and above.
I am getting false in GoogleSignInResult result.success().
Below is my Code:
public class SignUp extends FragmentActivity implements
GoogleApiClient.OnConnectionFailedListener {
private ImageView google_button
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestProfile()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//initializes view
initializeViews();
//facebook login end
google_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.e("data g+", result.toString());
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
Log.e(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
Log.e("authType", "googlePlus");
Log.e("authId", acct.getId());
Log.e("firstname", acct.getDisplayName());
Log.e("middlename", acct.getDisplayName());
Log.e("lastname", acct.getDisplayName());
Log.e("userpic", acct.getPhotoUrl() + "");
Log.e("email", acct.getEmail());
String[] DisplayName = acct.getDisplayName().split(" ");
String firstName = "";
String lastName = "";
if (DisplayName.length == 2) {
firstName = DisplayName[0];
lastName = DisplayName[1];
} else {
firstName = acct.getDisplayName();
}
String photoUrl = "";
if (acct.getPhotoUrl() != null) {
photoUrl = acct.getPhotoUrl().toString();
}
Bundle data = new Bundle();
data.putString("authType", "googlePlus");
data.putString("authId", acct.getId());
data.putString("firstname", firstName);
data.putString("middlename", "");
data.putString("lastname", lastName);
data.putString("userpic", photoUrl);
data.putString("email", acct.getEmail());
Intent intent = new Intent(SignUp.this, Register.class);
intent.putExtras(data);
startActivity(intent);
finish();
} else {
// Signed out, show unauthenticated UI.
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
public void initializeViews() {
register = (TextView) findViewById(R.id.register);
fb_button = (ImageView) findViewById(R.id.facebook_button);
google_button = (ImageView) findViewById(R.id.google_button);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("connectionResult", connectionResult.toString());
Toast.makeText(getApplicationContext(), getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
}

Categories

Resources