Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Google Plus and Facebook Authentication together in the same activity of Android project?

I need to to integrate both Facebook and Google Plus in the same activity but I'm not getting success in it. I have tried both in individual projects and they work fine but when I add both projects together my app gets crashed. Even I have tried them with custom buttons too but they don't work either. Currently my Facebook part is working fine but I get error when I click on Google's button at the time of login. I get error in these methods:

private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
        } catch (SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

and

private void signInWithGplus() {
    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        resolveSignInError();
    }
}

I'm implementing in this class:

public class LoginActivity extends Activity implements OnClickListener,
    ConnectionCallbacks, OnConnectionFailedListener {
// Your Facebook APP ID
private static String APP_ID = "XXXXXXXXXXXXXXX"; // Replace with your App
                                                    // ID
LinearLayout ll;
// Strings of Facebook
String fb_mUserId = "", fb_mUserToken = "", fb_mUserName = "",
        fb_mUserEmail = "", fb_verified_value = "", fb_Task_message;
boolean fb_verified, google_verified;
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
@SuppressWarnings("unused")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
EditText edittext_username, edittext_password;
Button Btn_login, Btn_register;
TextView Text_univesity, errorMsg, tv_forget_password;
LinearLayout ll_google, ll_fb;
static String Username, password, name, Twilio_Id = "",
        name_candidate = "", phone_no = "", email_candidate = "",
        country = "", mobile_verification = "", fb_id = "";
ImageView im;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
int id, Mode = 0, fb_clicked = 0, google_clicked = 0;
static int user_ids;
String IMEI_number;
GPSTracker gps;
static double latitude = 0.00, longitude = 0.00;
Context context;

private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "LoginActivity";
// Profile pic image size in pixels
// private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
 * A flag indicating that a PendingIntent is in progress and prevents us
 * from starting further intents.
 */
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
// Strings of Google Plus
String google_email="", google_id="", google_name="", google_verified_value="";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    IMEI_number = telephonyManager.getDeviceId();
    im = (ImageView) findViewById(R.id.header);
    mAsyncRunner = new AsyncFacebookRunner(facebook);


    if (Mode == 3) {
        if (login_details.contains("name")) {
            name = login_details.getString("name", "");
            Intercom.client().registerIdentifiedUser(
                    new Registration().withUserId(name));
        } else {
            Intercom.client().registerIdentifiedUser(
                    new Registration().withUserId("123456"));
        }
        // We're logged in, we can register the user with Intercom
        // Carry on as normal
        Intent mode = new Intent(LoginActivity.this, MenuItems.class);
        startActivity(mode);
        finish();
    } else {
        edittext_password = (EditText) findViewById(R.id.et_login_password);
        Btn_login = (Button) findViewById(R.id.btn_login);
        Btn_register = (Button) findViewById(R.id.btn_login_register);
        ll_fb = (LinearLayout) findViewById(R.id.login_fb);
        ll_google = (LinearLayout) findViewById(R.id.login_google);
        tv_forget_password = (TextView) findViewById(R.id.tv_login_forget_password);
        Btn_login.setOnClickListener(this);
        Btn_register.setOnClickListener(this);
        ll_fb.setOnClickListener(this);
        ll_google.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);

        // Initializing google plus api client
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_PROFILE).build();
    }

}

@Override
public void onClick(View v) {
    switch (v.getId()) {

    case R.id.btn_login:
   // Direct Login Process
        break;
    case R.id.btn_login_register:
        // Direct register process
        finish();
        break;
    case R.id.login_fb:
        fb_clicked++;
        loginToFacebook();
        getProfileInformation();
        if (!fb_mUserEmail.equals("")) {
            if (fb_verified == true) {
                fb_verified_value = "1";
            } else {
                fb_verified_value = "0";
            }
            new FacebookAsynTask().execute();
        }
        break;
    case R.id.login_google:
        google_clicked++;
        signInWithGplus();
    //  getGoogleProfileInformation();
        if (!google_email.equals("")) {
            if (google_verified == true) {
                google_verified_value = "1";
            } else {
                google_verified_value = "0";
            }
            new GoogleAsynTask().execute();
        }
        break;
    case R.id.tv_login_forget_password:
        break;

    }
}

@Override
protected void onResume() {
    super.onResume();
}

protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

/** LOGIN TO FACEBOOK */
public void loginToFacebook() {
    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);

    if (access_token != null) {
        facebook.setAccessToken(access_token);
        Log.d("FB Sessions", "" + facebook.isSessionValid());
        Toast.makeText(LoginActivity.this, "FIRST CASE", Toast.LENGTH_SHORT)
                .show();
        getProfileInformation();
    }

    if (expires != 0) {
        facebook.setAccessExpires(expires);
    }

    if (!facebook.isSessionValid()) {
        facebook.authorize(this,
                new String[] { "email", "publish_actions" },
                new DialogListener() {

                    @Override
                    public void onCancel() {
                        // Function to handle cancel event
                    }

                    @Override
                    public void onComplete(Bundle values) {
                        // Function to handle complete event
                        // Edit Preferences and update facebook acess_token
                        SharedPreferences.Editor editor = mPrefs.edit();
                        editor.putString("access_token",
                                facebook.getAccessToken());
                        editor.putLong("access_expires",
                                facebook.getAccessExpires());
                        editor.commit();
                        Toast.makeText(LoginActivity.this, "SECOND CASE",
                                Toast.LENGTH_SHORT).show();
                        getProfileInformation();

                        // Making Login button invisible

                    }

                    public void onError(DialogError error) {
                        // Function to handle error
                    }

                    public void onFacebookError(FacebookError fberror) {
                        // Function to handle Facebook errors
                    }

                });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (fb_clicked != 0) {
        facebook.authorizeCallback(requestCode, resultCode, data);
        fb_clicked = 0;
    }
    else if (google_clicked != 0) {

        if (requestCode == RC_SIGN_IN) {
            if (resultCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
        google_clicked = 0;
    }
}

/**
 * Get Profile information by making request to Facebook Graph API
 * */
public void getProfileInformation() {
    try {

        JSONObject profile = Util.parseJson(facebook.request("me"));
        Log.e("Profile", "" + profile);
        fb_mUserId = profile.getString("id");
        fb_verified = profile.getBoolean("verified");
        fb_mUserToken = facebook.getAccessToken();
        fb_mUserName = profile.getString("name");
        fb_mUserEmail = profile.getString("email");

        runOnUiThread(new Runnable() {

            public void run() {

                Log.e("FaceBook_Profile", "" + fb_mUserId + "\n"
                        + fb_mUserToken + "\n" + fb_mUserName + "\n"
                        + fb_mUserEmail);
            }
        });

    } catch (FacebookError e) {

        e.printStackTrace();
    } catch (MalformedURLException e) {

        e.printStackTrace();
    } catch (JSONException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
}

/** AsyncTask of Direct Login */


class FacebookAsynTask extends AsyncTask<Void, Void, Void> {

}

/** GOOGLE's CODE STARTS */
/**
 * Sign-in into google
 * */
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) {
    mSignInClicked = false;
    Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

    // Get user's information
    getGoogleProfileInformation();

    // Update the UI after signin
    // updateUI(true);

}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
    // updateUI(false);
}

/**
 * Fetching user's information name, email, profile pic
 * */
private void getGoogleProfileInformation() {
    try {
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi
                    .getCurrentPerson(mGoogleApiClient);
            google_name = currentPerson.getDisplayName();
            google_id = currentPerson.getId();
            google_verified = currentPerson.isVerified();
            String personPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            google_email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e(TAG, "Name: " + google_name + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + google_email
                    + ", Image: " + personPhotoUrl);

            // by default the profile url gives 50x50 px image only
            // we can replace the value with whatever dimension we want by
            // replacing sz=X

        } else {
            Toast.makeText(getApplicationContext(),
                    "Person information is null", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

class GoogleAsynTask extends AsyncTask<Void, Void, Void> {
}

It would be great if anybody helps me in it.

Thanks.

like image 762
Anshul Tyagi Avatar asked Jul 03 '15 12:07

Anshul Tyagi


2 Answers

I've solved my problem myself yesterday by adding few lines in onClick part

if (mGoogleApiClient.isConnected()) {
            getProfileInformation();
        } else {
            signInWithGplus();
            getProfileInformation();
        } 
}
like image 138
Anshul Tyagi Avatar answered Nov 08 '22 18:11

Anshul Tyagi


It appears that if you call signInWithGplus() the first time, it'll try to access mConnectionResult which is null at that point.

The reason for that is because you're only setting it in onConnectionFailed() which would have not been called.

like image 4
Nyx Avatar answered Nov 08 '22 16:11

Nyx