在Android注销后重新登录Google时出错

时间:2016-02-22 06:02:51

标签: android google-login

您好我在我的应用程序中使用Google登录它工作正常但是每当我退出时我尝试了许多解决方案来退出但它对我不起作用,如果我再点击Google登录按钮,那么应用程序崩溃。< / p>

这是我的登录代码

empty

现在我需要从其他活动注销使用此代码

用于退出

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();
        }
      }
   }

}

这种方法对我不起作用。 即使我明确了偏好并尝试使用谷歌进行新登录,然后应用程序崩溃。

Logcat错误

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) {

   }
}

1 个答案:

答案 0 :(得分:3)

先检查空值

set.seed(1) 

dfmaker <- function() {
        setNames(
                data.frame(
                        replicate(5, sample(c(NA, 300:500), 4, TRUE), FALSE)), 
                c('pn_ds_ms_fa_th_hrs','rn_ds_ms_wi_th_stu' ,'adn_ds_ms_wi_th_hrs','pn_ds_ms_wi_th_hrs' ,'rn_bsn_ds_ms_wi_th_hrs'))
}


d <- dfmaker()

library(dplyr)

d <- tbl_df(d)

grepl_vec_pattern = Vectorize(grepl, 'pattern')

calcterm = function(s) {
        require(pryr)
        s = as.character(s)
        grepped_patterns = grepl_vec_pattern(s, pattern = c('_sp', '_su', '_fa', '_wi'))
        stopifnot(any(rowSums(grepped_patterns) == 1))   # Ensure that there is exactly one match
        reduce_to_colname_with_true = apply(grepped_patterns, 1, compose(names, which))
        lut_table = c('_sp' = 'spring', '_su' = 'summer', '_fa' = 'fall', '_wi' = 'winter')
        lut_table[reduce_to_colname_with_true]
}

select(d, matches("^pn_|^adn_|^bsn_"), -starts_with("rn_bsn")) %>%  # all the pn, adn, bsn programs, for all information 
        select(contains("_hrs") ) %>%   # takes out just the hours
        gather(placement, hours) %>%  # flip it!
        group_by(placement) %>%  # gather all the schools into a single observation (replicated placement values at this point)
        summarise(sumHours = sum(hours, na.rm=T)) %>%
        mutate(term = calcterm(placement))

并为Logout调用bellow方法

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();
            }
        }
}
相关问题