Google Sign: GoogleAPIClient not connecting - android

I integrated google sign in in my app, that works well on L and M devices. But for some reason not on KitKat and below. I debugged it and it always calls onConnectionFailed, but why? Below is the LoginActivity:
public class LoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_google = (CircleButton) findViewById(R.id.btn_login_google);
btn_google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnecting()) {
mShouldResolve = true;
resolveSignInError();
}
}
});
//Build GoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.addScope(new Scope(Scopes.EMAIL))
.addScope(new Scope(Scopes.PLUS_LOGIN))
.addScope(new Scope(Scopes.PLUS_ME))
.build();
mGoogleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mShouldResolve = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
protected void onStart() {
super.onStart();
//connect GoogleApiClient
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
//disconnect GoogleApiClient
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/*
Used for resolving errors during signIn
*/
private void resolveSignInError() {
if (connectionResult.hasResolution()) {
try {
mIntentInProgress = true;
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
/*
When the GoogleApiClient object is unable to establish a connection onConnectionFailed() is called
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
connectionResult = result;
if (mShouldResolve) {
resolveSignInError();
}
}
}
/*
on the successfull connection onConnected is called
*/
#Override
public void onConnected(Bundle arg0) {
mShouldResolve = false;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}else{
get_user_details();
}
}
private void get_user_details(){
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person person = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
personName_google = person.getDisplayName();
email_google = Plus.AccountApi.getAccountName(mGoogleApiClient);
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 100;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.GET_ACCOUNTS)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.GET_ACCOUNTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.GET_ACCOUNTS},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.GET_ACCOUNTS},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.GET_ACCOUNTS)
== PackageManager.PERMISSION_GRANTED) {
get_user_details();
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
dialog_general_prog.dismiss();
}
return;
}
}
}
}

Related

Google Play network connection doesnt work

I am trying to connect my App to Google Play Services, for to add games achievements, but it doesn´t connect. It returns me this message:
Failed to sign in. Please check your network connection and try again.
I reinstalled Google Services, and it didn´t fix the problem.
Here is my code.
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener
{
public static GoogleApiClient googleApiClient;
private static int RC_SIGN_IN = 9001;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.build();
}
#Override
protected void onStart() {
try
{
super.onStart();
googleApiClient.connect();
}catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onStop() {
try
{
super.onStop();
googleApiClient.disconnect();
}catch (Exception e)
{
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode,Intent intent)
{
if (requestCode == RC_SIGN_IN)
{
mSignInClicked = false;
mResolvingConnectionFailure = false;
if (resultCode == RESULT_OK)
{
googleApiClient.connect();
}
else
{
BaseGameUtils.showActivityResultError(this, requestCode, resultCode, R.string.error_conectar_google_juegos2);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("STATE_RESOLVING_ERROR", false);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
if (mResolvingConnectionFailure)
{
return;
}
if (mSignInClicked || mAutoStartSignInflow)
{
mAutoStartSignInflow = false;
mSignInClicked = false;
mResolvingConnectionFailure = true;
if (!BaseGameUtils.resolveConnectionFailure(this,googleApiClient, connectionResult,RC_SIGN_IN, R.string.error_conectar_google_juegos1))
{
mResolvingConnectionFailure = false;
}
}
}
}
The execution flow is the next:
onCreate()
onStart()
onConnectionFailed()
onSaveinstanceState()
It asks for my Google Account
onActivityResult()
Here it goes to the "ELSE" of the onActivityResult().
When it fails, it shows the message I said before.
I have good internet connection on my device, and I use Android Games of Google Games with no problem. What can be happening?
Thank you so much.

Error in Re-login with Google after logout in Android

Hi I use Google login in my app it works fine but whenever I logging out I tried many solution for logging out but it doesn't works for me and if I further clicks on Google login button then app crashes.
Here is my code for Login
public class LoginActivity extends Activity implements AsyncInterface,
OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
EditText etLoginEmail, etLoginPassword;
Button btnLoginSubmit, btnLoginSignup;
TextView txtLoginForgotPass;
LoginResponseMain loginResponseMain;
/* For Google */
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
// Google Sign In Button
btnSignIn.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (AppMethod.getBooleanPreference(LoginActivity.this, AppConstant.PREF_FIRST_LOGIN)) {
//startActivity(new Intent(LoginActivity.this, HomePage.class));
} else {
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
public void init() {
loginResponseMain = new LoginResponseMain();
btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
}
#Override
public void onWSResponse(String json, String WSType) {
if (WSType == AppConstant.WS_LOGIN_G) {
try {
Log.e("Json", json);
JSONObject jobj = new JSONObject(json);
boolean error = jobj.getBoolean("error");
if (!error) {
JSONArray jsonArray = jobj.getJSONArray("user");
JSONObject jobjUser = jsonArray.getJSONObject(0);
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_FACEBOOK_ID, jobjUser.getString("facebook_id"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_GOOGLE_ID, jobjUser.getString("google_plus_id"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_EMAIL, jobjUser.getString("email"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_FNAME, jobjUser.getString("first_name"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_LNAME, jobjUser.getString("last_name"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_UPDATED_AT, jobjUser.getString("updated_at"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_CREATED_AT, jobjUser.getString("created_at"));
AppMethod.setStringPreference(LoginActivity.this, AppConstant.PREF_USER_ID, String.valueOf(jobjUser.getInt("id")));
Intent i = new Intent(LoginActivity.this, TermsForUseActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(LoginActivity.this, AppConstant.SOMETHING_WRONG_TRY_AGAIN, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
getProfileInformation();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
// Login Button Click
case R.id.sign_in_button:
signInWithGplus();
break;
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result2 = googleAPI.isGooglePlayServicesAvailable(this);
if (result2 != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result2)) {
googleAPI.getErrorDialog(this, result2, 0).show();
}
}
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult; // Store the ConnectionResult for later usage
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to resolve all errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
/* Fetching user's information name, email, profile pic */
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
String url = AppConstant.LOGIN_WITH_G;
// WS for google login data submit.
if (AppMethod.isNetworkConnected(LoginActivity.this)) {
String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String device_token = AppMethod.registerForGCM(LoginActivity.this);
Uri.Builder values = new Uri.Builder()
.appendQueryParameter("first_name", personName)
.appendQueryParameter("email", email)
.appendQueryParameter("udid", android_id)
.appendQueryParameter("login_type", "0")
.appendQueryParameter("device_token", device_token)
.appendQueryParameter("google_plus_id", currentPerson.getId());
WsHttpPostWithNamePair wsHttpPost = new WsHttpPostWithNamePair(LoginActivity.this, AppConstant.WS_LOGIN_G, values);
wsHttpPost.execute(url);
} else {
Toast.makeText(LoginActivity.this, AppConstant.NO_INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
}
Now i need to signout from another activity use this code
For Logging out
public class HomePage extends TabActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult> {
DrawerLayout dLayout;
LinearLayout right_layout;
Button btnViewProfile, btnLogout;
//Google
GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private ConnectionResult mConnectionResult;
private static final int RC_SIGN_IN = 0;
private boolean mSignInClicked;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.home_page);
llHomePageMain = (LinearLayout) findViewById(R.id.llHomePageMain);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
mGoogleApiClient.connect();
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
right_layout = (LinearLayout) findViewById(R.id.right_layout);
btnViewProfile = (Button) findViewById(R.id.btnViewProfile);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnViewProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("Right Layout", "Profile");
dLayout.closeDrawer(Gravity.END);
Intent i = new Intent(HomePage.this, ProfileActivity.class);
startActivity(i);
}
});
btnLogout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AppMethod.clearApplicationData(HomePage.this);
googlePlusLogout();
loginSessionClear();
}
}
});
}
#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
}
private void resolveSignInError() {
if (mConnectionResult != null)
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
private void googlePlusLogout() {
if (mGoogleApiClient != null)
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!connectionResult.hasResolution()) {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result2 = googleAPI.isGooglePlayServicesAvailable(this);
if (result2 != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result2)) {
googleAPI.getErrorDialog(this, result2, 0).show();
}
}
return;
}
if (!mIntentInProgress) {
mConnectionResult = connectionResult;
if (mSignInClicked) {
resolveSignInError();
}
}
}
#Override
public void onBackPressed() {
dLayout.closeDrawers();
super.onBackPressed();
}
public void loginSessionClear() {
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_EMAIL, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_FNAME, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_LNAME, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_UDID, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_DEVICE_TOKEN, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_UPDATED_AT, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_CREATED_AT, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_GOOGLE_ID, "");
AppMethod.setStringPreference(HomePage.this, AppConstant.PREF_USER_ID, String.valueOf(""));
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onResult(People.LoadPeopleResult loadPeopleResult) {
}
}
This method doesnt work for me.
Even if i clear preference and try for new login with google then app crashes.
Logcat Error
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.common.ConnectionResult.hasResolution()' on a null object reference
Check null first
private void resolveSignInError() {
if (mConnectionResult != null)
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
and call bellow method for Logout
private void googlePlusLogout() {
if (mGoogleApiClient != null)
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}

Problems with google plus sign in android

I've added Google plus sign in to my app. When i click the sign in with google button, the app freezes, and stops responding. when i kill the app and restart it, the sign in happens without any issue. What is going wrong?
The code is below.
Layout
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:elevation="10dp"/>
and the Java code is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
mSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
});
mSignInButton.setSize(SignInButton.SIZE_WIDE);
}
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
startIntentSenderForResult(mConnectionResult.getResolution()
.getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the
// default
// state and attempt to connect to get an updated
// ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
// Store the ConnectionResult so that we can use it later when the
// user clicks
// 'sign-in'.
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
Log.e("Connection","success");
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
The logcat showed that the result code is -1 and intent is null in onActivityResult.And the mGoogleApi.connect() is called again. the app just freezes at that stage, and the callbacks aren't fired. what am I doing wrong?
I m using like this
private boolean mSignInClicked;
private GoogleApiClient mGoogleApiClient;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
write the above code in onCreate()...
onClick method of gplus button
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
mSignInClicked = false;
// Get user's information
getProfileInformation();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String reg_id = currentPerson.getId();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e("Google plus responce", "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl+"REG ID " +reg_id );
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
}
In onactivityfor result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FbLogin", "Result Code is = " + resultCode +"");
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
Custom Button
<ImageView
android:id="#+id/btn_gplus"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:layout_weight="1"
android:background="#drawable/btn_cha_gmail" />
Hope this is will work fine to you....Happeee Programming!!!!!!
I too had the same problem. There was some logical mistake in my onActivityResult.
Check your onActivityResult method. Then only your problem would be solved.

Android Google sign in stuck in loop

I am implementing a Google plus sign in from a Fragment.
I am getting an Infinite loop of the Google sign in my dialog.
Code:
Activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("TEST", "requestCode: " + requestCode + ", resultCode: " + resultCode);
if (FragmentLogIn.RC_SIGN_IN == requestCode){
FragmentLogIn fragment = (FragmentLogIn) getSupportFragmentManager().findFragmentById(mainContent.getId());
fragment.onActivityResult(requestCode, resultCode, data);
} else{
super.onActivityResult(requestCode, resultCode, data);
}
}
Fragment:
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent)
{
Log.e("GOOGLE+", "requestCode: " + requestCode + "responseCode = " + responseCode);
if (requestCode == RC_SIGN_IN) {
if (responseCode != Activity.RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle bundle)
{
Log.e("GOOGLE TEST", "onConnected");
//get user info
try{
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
new RetrieveTokenTask().execute(email);
} else {
Log.e("GOOGLE+", "info = null");
}
} catch (Exception e) {
e.printStackTrace();
}
mSignInClicked = false;
}
#Override
public void onConnectionSuspended(int i)
{
Log.e("GOOGLE TEST", "onConnectionSuspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), getActivity(),
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onClick(View view)
{
if (view.getId() == R.id.google_sign_in_button) {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
} else if (view.getId() == R.id.google_sign_out_button) {
revokeGplusAccess();
}
}
private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String accountName = params[0];
Log.e("accountName", accountName);
String scopes = "oauth2:profile "+Scopes.PLUS_LOGIN;;
String token = null;
try {
if (getActivity() != null)
token = GoogleAuthUtil.getToken(getActivity().getApplicationContext(), accountName, scopes);
} catch (IOException e) {
Log.e("GOOGLE+", e.getMessage());
} catch (UserRecoverableAuthException e) {
startActivityForResult(e.getIntent(), 1);
} catch (GoogleAuthException e) {
Log.e("GOOGLE+", e.getMessage());
}
return token;
}
#Override
protected void onPostExecute(String s) {
Log.d("TOKEN", "token: " + s);
}
}
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e("GOOGLE+", "User access revoked!");
mGoogleApiClient.connect();
}
});
}
}
This code works when it's written in an Activitybut when I switched it to a Fragment I get an infinite loop.
What I'm doing wrong? Does any body have a different example of login with Google plus using an access token?
Thanks,
Ilan
The infinite loop problem comes when you disconnect the googleApiClient in onStop(). You should do that only in onDestroy().
Hope it helps.
Remove the line
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
from onConnectionFailed(ConnectionResult result) method and the infinite loop wont happen anymore.

Strange error while integrating Google plus

I am integrating google plus in my application from this URL https://developers.google.com/+/mobile/android/sign-in but i am not able to get chooser of google plus account to login and in ConnectionResult i always get ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{4223c668: android.os.BinderProxy#4224b9c0}}...
I tried lots of links and created and deleted client id its not working for me
Here is my Code
#Override
protected void onCreate(Bundle savedInstanceState) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
btnGooglePlus = (SignInButton) findViewById(R.id.sign_in_button);
btnGooglePlus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in_button
&& !mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!mIntentInProgress) {
// Store the ConnectionResult so that we can use it later when the
// user clicks
// 'sign-in'.
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
/* A helper method to resolve the current ConnectionResult error. */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
// The intent was canceled before it was sent. Return to the
// default
// state and attempt to connect to get an updated
// ConnectionResult.
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
You don't do anything in your OnClickListener.
You need to call resolveSignInError() from onClick, which will recognize the SIGN_IN_REQUIRED and start the login flow accordingly.

Categories

Resources