Search code examples
javaandroidfacebook-loginandroid-facebookfacebook-sdk-4.0

Android Facebook login callbacks never fire


I created an activity with facebook login button and registered callbacks in onCreate method. Now when I press login button and login through facebook I expect my callbacks to be fired but they don't. What am I doing wrong?

    CallbackManager callbackManager;
    LoginButton loginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        FacebookSdk.sdkInitialize(getApplicationContext());

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("user_friends");
        callbackManager = CallbackManager.Factory.create();

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "Cancelled!", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();
            }
        });
    }

Solution

  • Since you are posting code for callbacks not working.

    1. I am assuming that you have created a project on facebook developer console, obtained development hashes and status is set to public.

    2. Your application manifest has meta-data tag for application id.

    So further coming to your code, add onActivityResult() in your activity and forward it to your callbackManager. (Facebook Documentation)

    If login succeeds, the LoginResult parameter has the new AccessToken, and the most recently granted or declined permissions.

    You don't need a registerCallback for login to succeed, you can choose to follow current access token changes with the AccessTokenTracker class described below.

    Then in onActivityResult() forward the login results to the callbackManager created in onCreate():

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