Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 224
Sam Avatar asked Feb 22 '16 06:02

Sam


1 Answers

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();
            }
    }
like image 93
Bajirao Shinde Avatar answered Sep 30 '22 15:09

Bajirao Shinde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!