Android get google user Birthday and Gender - android

Main task is to get users Age and Gender on current device (for ads targeting).
I knew that this question could be possible duplicate, but none of posted answers didn't help me.
From my code i'm getting correct users Name but birthday = null, gender = 0.
Tested on my test device with valid Google Account with public Birthday and Gender.
private static final int RC_SIGN_IN = 1009;
private GoogleApiClient googleApiClient;
private int connectionFailedCounter;
private void googleSignIn() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.addApi(Plus.API)
.build();
googleApiClient.connect();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
googleSignIn();
}
#Override
protected void onStart() {
super.onStart();
if (googleApiClient == null)
googleSignIn();
else if (!googleApiClient.isConnecting())
googleApiClient.connect();
}
#Override
protected void onStop() {
if (googleApiClient != null && googleApiClient.isConnected())
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Toast.makeText(this, "google+ connected", Toast.LENGTH_LONG).show();
Person currentPerson = Plus.PeopleApi.getCurrentPerson(googleApiClient);
if (currentPerson != null) {
//NotificationManager is my own class,
//sendNotification(Context context, Class classToOpenOnClick, String title, String message)
NotificationManager.sendNotification(this, null, currentPerson.getName().getFamilyName(),
String.format(Locale.getDefault(), "bir = %s, gen = %d", currentPerson.getBirthday(), currentPerson.getGender()));
}
else Toast.makeText(this, "getCurrentPerson = null", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e(TAG, "connection failed (" + connectionResult.getErrorCode() + ")");
Toast.makeText(this, "google+ failed", Toast.LENGTH_LONG).show();
if (connectionResult.hasResolution()) {
try {
connectionFailedCounter++;
if (connectionFailedCounter < 2)
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == RC_SIGN_IN) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(googleApiClient);
NotificationManager.sendNotification(this, null, currentPerson.getName().getFamilyName(),
String.format(Locale.getDefault(), "bir = %s, gen = %d", currentPerson.getBirthday(), currentPerson.getGender()));
if (!googleApiClient.isConnected())
googleApiClient.connect();
}
}
}

Related

How to Resolve SIGN_IN_REQUIRED error in google plus integration?

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

Google + plus sign in not working after android 6 release

So, before android 6 marshmallow release, google + sign in worked perfectly. After release, Im having issues like permissions, onConnectionFailed, etc... Does anybody has a solution how to fix this? Im calling google sign in methods from fragment. Here is the code:
Fragment:
#Override
public void onConnected(Bundle bundle) {
Log.d("GoogleApiClient", "onConnected");
mShouldResolve = false;
new RetrieveTokenTask().execute(Plus.AccountApi.getAccountName(mGoogleApiClient));
}
#Override
public void onConnectionSuspended(int i) {
Log.d("GoogleApiClient", "onConnectionSuspended " + String.valueOf(i));
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("GoogleApiClient", "onConnectionFailed");
Log.d("GoogleApiCLient", connectionResult.toString());
ViewUtils.hideProgressDialog();
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e("LoginFragment", "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("RequestCode", String.valueOf(requestCode));
Log.i("ResultCode", String.valueOf(resultCode));
try {
Log.i("Intent", data.getAction());
} catch (Exception e) {
}
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
ViewUtils.showProgressDialog(getActivity(), getActivity().getResources().getString(R.string.loading_dialog_str));
if (resultCode != getActivity().RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
if (mGoogleApiClient.isConnected()) {
new RetrieveTokenTask().execute(Plus.AccountApi.getAccountName(mGoogleApiClient));
}
} else {
//facebook
Log.d("Login", "FaceBook");
mCallbackManagerFacebook.onActivityResult(requestCode, resultCode, data);
}
}
private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
private static final String TAG = "RetrieveAccessToken";
private static final int REQ_SIGN_IN_REQUIRED = 55664;
#Override
protected String doInBackground(String... params) {
String accountName = params[0];
String scopes = "oauth2:profile";
String token = null;
try {
token = GoogleAuthUtil.getToken(getActivity(), accountName, scopes);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (UserRecoverableAuthException e) {
startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
} catch (GoogleAuthException e) {
Log.e(TAG, e.getMessage());
}
return token;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Token", "Token Value: " + s);
if (s == null) {
ViewUtils.hideProgressDialog();
ViewUtils.showToastMessage(getActivity(), getActivity().getResources().getString(R.string.login_error));
} else {
loginGoogleUser(s);
}
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
}
}
}
and activities on result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LoginFragment loginFragment = (LoginFragment) getSupportFragmentManager().findFragmentByTag("MyProfileFragment");
if (loginFragment != null) {
loginFragment.onActivityResult(requestCode, resultCode, data);
}
}
Ok, so, first of all, you need to change all of your dependencies of google play services to 8.1.0, also, build.gradle to the newest version, targeted sdk 23, comiled version 23, etc. So, basicaly, check your gradle. After that, you need to change your mGoogleApiClient to :
mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).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();
And finally, you need to include permissions you need for sdk>= 23. To do that, create
private static String ACCOUNT_PERMISSIONS[] = new String[]{
Manifest.permission.GET_ACCOUNTS
};
Here is a good tutorial on how to get permissions for sdk >= 23:
https://github.com/googlesamples/android-RuntimePermissions

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.

Google+ Login Not working properly on Android fragment

I am working with google+ login to my application and when i done it using a activity its work charm and after that i move my code into a fragment and after that when i try to login to google+ its not working i have to open the fragment activity 2 times to login to the google+ can anyone tell me what happen the code to the fragment is added below
public class GooglePluseFragment extends Fragment implements
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
private static final String TAG = "MainActivity";
private static final int PROFILE_PIC_SIZE = 800;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut;
private Context mContext;
private Activity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = getActivity();
mContext = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.compund_google_pluse_fragment,
container, false);
btnSignIn = (SignInButton) view.findViewById(R.id.btn_sign_in);
btnSignOut = (Button) view.findViewById(R.id.btn_sign_out);
sharedPref = view.getContext().getSharedPreferences(
Constantz.SHEARED_PREFEREANCE, Context.MODE_PRIVATE);
mGoogleApiClient = new GoogleApiClient.Builder(view.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signInWithGplus();
}
});
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOutFromGplus();
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != Activity.RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
mActivity, 0).show();
Log.e(TAG, "" + result.getErrorCode());
return;
}
if (!mIntentInProgress) {
mConnectionResult = result;
if (mSignInClicked) {
Log.e(TAG, "" + result.getErrorCode());
resolveSignInError();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
getProfileInformation();
updateUI(true);
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
btnSignOut.setVisibility(View.VISIBLE);
} else {
btnSignIn.setVisibility(View.VISIBLE);
btnSignOut.setVisibility(View.GONE);
}
}
/**
* 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(mActivity,
RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
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 personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl + " user id:"
+ currentPerson.getId());
} else {
Toast.makeText(mContext, "Person information is null",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}
}
this is how i added framgent in the fragment activity
pluseFragment = new GooglePluseFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.pluse_frame_layout, pluseFragment);
transaction.commit();
can somebody tell me what i have done wrong ? why i have to open the activity two times to login thank you
Finally found the answer, Problem was when the result activity call in the fragment was catch by the parent activity so you have to manually redirect the result to your fragment. Just have to add this line in your Parent Fragment Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GooglePluseFragment.RC_SIGN_IN) {
GooglePluseFragment fragment = (GooglePluseFragment) getSupportFragmentManager()
.findFragmentById(R.id.pluse_frame_layout);
fragment.onActivityResult(requestCode, resultCode, data);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Easy Solution for this ::
just create the static method in fragment
"
public static myOnActivityResult(int requestCode, int resultCode, Intent data){
.....Enter same code
}
and
call this method from Parant Activity on
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
.....
MyFragment.myOnActivityResult(requestCode,resultCode,data)
}
thats it

Categories

Resources