0

I am trying to use Facebook login in my AppCompatActivity. But when the user presses the login button and logs in and is returned to my activity, its being called again:

    //FACEBOOK
        private CallbackManager callbackManager;
        private Button loginButton;



    onCreate:
    //Facebook
            callbackManager = CallbackManager.Factory.create();
            loginButton = (Button)findViewById(R.id.login_button);
            loginButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // Perform action on click
                    if(Util.isNetworkConnectedNotify(context, LandingActivity.this)) { loginFacebook();  }
                }
            });



       @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            callbackManager.onActivityResult(requestCode, resultCode, data);

        }



   private void loginFacebook() {

            List<String> permissionNeeds = Arrays.asList("public_profile", "user_friends", "email");
            LoginManager.getInstance().logInWithReadPermissions(LandingActivity.this, permissionNeeds);
            LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    fbToken = loginResult.getAccessToken().getToken();

                    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject object, GraphResponse response) {

                                    if (response.getError() != null) {
                                        // handle error
                                        System.out.println("ERROR");
                                        if (dialog != null) dialog.dismiss();
                                        Dialogs.errorDialog(LandingActivity.this);

                                    } else {
                                        System.out.println("Success");
                                        try {
                                            String jsonresult = String.valueOf(object);
                                            System.out.println("JSON Result" + jsonresult);

                                            fbEmail = object.getString("email");
                                            fbId = object.getString("id");
                                            fbName = object.getString("name");
                                            fbGender = object.getString("gender");


                                            //Do Login ->>>
                                            << CALL MY API TO DO USER LOGIN >>

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


                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,email,gender, birthday");
                    request.setParameters(parameters);
                    request.executeAsync();
                }

                @Override
                public void onCancel() {
                    if (dialog != null) dialog.dismiss();
                }

                @Override
                public void onError(FacebookException e) {
                    if (dialog != null) dialog.dismiss();
                }
            });


    }//end loginFacebook


//LifeCycles
/** Called when leaving the activity */
@Override
public void onPause() {
    super.onPause();
    // Logs 'app deactivate' App Event.
    AppEventsLogger.deactivateApp(this);
}

/** Called when returning to the activity */
@Override
public void onResume() {
    super.onResume();

    // Logs 'install' and 'app activate' App Events.
    AppEventsLogger.activateApp(this);
}
Huey
  • 5,110
  • 6
  • 32
  • 44
Thiago
  • 12,778
  • 14
  • 93
  • 110
  • @Hello. Did you find out the reason? I'm facing the same problem. `onSuccess` method is called twice – TOP Aug 22 '17 at 07:11

1 Answers1

0

If you are working with default facebook button than use this code. No need to set onclick event of button. It's works successfully.

place your code in onSuccess method which you want after successful login.

loginButton = (LoginButton) findViewById(R.id.login_button);

List < String > permissionNeeds = Arrays.asList("user_photos", "email",
 "user_birthday", "public_profile", "AccessToken");
loginButton.registerCallback(callbackManager,
new FacebookCallback < LoginResult > () {@Override
 public void onSuccess(LoginResult loginResult) {

  System.out.println("onSuccess");

  String accessToken = loginResult.getAccessToken()
   .getToken();
  Log.i("accessToken", accessToken);

  GraphRequest request = GraphRequest.newMeRequest(
  loginResult.getAccessToken(),
  new GraphRequest.GraphJSONObjectCallback() {@Override
   public void onCompleted(JSONObject object,
   GraphResponse response) {
    Log.i("LoginActivity", response.toString());
    try {
     id = object.getString("id");
     try {
      URL profile_pic = new URL(
       "http://graph.facebook.com/" + id + "/picture?type=large");
      Log.i("profile_pic",
      profile_pic + "");

     } catch (MalformedURLException e) {
      e.printStackTrace();
     }
     String name = object.getString("name");
     String email = object.getString("email");
     String gender = object.getString("gender");
     String birthday = object.getString("birthday");
    } catch (JSONException e) {
     e.printStackTrace();
    }
   }
  });
  Bundle parameters = new Bundle();
  parameters.putString("fields",
   "id,name,email,gender, birthday");
  request.setParameters(parameters);
  request.executeAsync();
 }

 @Override
 public void onCancel() {
  System.out.println("onCancel");
 }

 @Override
 public void onError(FacebookException exception) {
  System.out.println("onError");
  Log.v("LoginActivity", exception.getCause().toString());
 }
});
Harvi Sirja
  • 2,472
  • 2
  • 18
  • 19
  • for custom facebook login button check my answer here. http://stackoverflow.com/questions/31327897/custom-facebook-login-button-android/31332928#31332928 – Harvi Sirja Aug 01 '15 at 04:14
  • Ok than also you can use same method which is in answer. You can see that I am just use same way in both default and custom button. Difference is only event handling. – Harvi Sirja Aug 01 '15 at 11:07