Trent Pierce
Trent Pierce

Reputation: 397

Android Facebook SDK ShareDialog not returning a callback

I am converting my application from the native Share Api to a ShareDialog. THe dialog displays correctly, but my application does not receive a callback saying that the post was completed / failed / canceled. I am using this ShareDialog in a fragment, and I believe that may be part of my issue. Why is the callback not being received?

Here's the code...

public class FacebookSocialSelector extends SocialSelector {
    private static final String FACEBOOK_EMAIL_PREFERENCE = "facebook_email";
    private final CallbackManager mCallbackManager;
    private String mFbEmail;
    ShareDialog shareDialog;

    public FacebookSocialSelector(ShareFragment fragment, View v, ImageView iconView) {
        super(fragment, v, iconView);


        // Social login
        FacebookSdk.sdkInitialize(fragment.getContext().getApplicationContext());
        mCallbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().registerCallback(mCallbackManager,
                mFacebookLoginCallback);
        shareDialog = new ShareDialog(mFragment.getActivity());
        setBackgroundDisabledDrawable(R.drawable.sharebtn_left_disable);
        setBackgroundEnabledDrawable(R.drawable.sharebtn_left_enable);
        setDisabledDrawable(R.drawable.facebook_disable);
        setEnabledDrawable(R.drawable.facebook_enable);
    }

    @Override
    public void login() {
        // Check for existing login
        final String fbEmail;
        if (mFbEmail == null) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(mFragment.getActivity());
            fbEmail = prefs.getString(FACEBOOK_EMAIL_PREFERENCE, null);
        } else {
            fbEmail = mFbEmail;
        }

        if (AccessToken.getCurrentAccessToken() != null && fbEmail != null) {
            if (Profile.getCurrentProfile() != null) {
                finishLogin(true);
                mFragment.fbInfo(Profile.getCurrentProfile().getId(),
                        Profile.getCurrentProfile().getName(), fbEmail);
            } else {
                new ProfileTracker() {
                    @Override
                    protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                        finishLogin(true);
                        mFragment.fbInfo(currentProfile.getId(),
                                currentProfile.getName(), fbEmail);
                        Profile.setCurrentProfile(currentProfile);
                        stopTracking();
                    }
                };
                Profile.fetchProfileForCurrentAccessToken();
            }
            return;
        }

        LoginManager.getInstance().logInWithReadPermissions(mFragment.getActivity(),
                Arrays.asList("public_profile", "email"));
    }

    public void finishLogin(boolean success) {
        if (success) {
            select();
            mFragment.loginSuccess();
        } else {
            mFragment.loginFailed("Could not login to FaceBook");
        }
    }



 public void doPost(String message, Bitmap bitmap) {
        ShareDialog shareDialog = new ShareDialog(mFragment.getActivity());
        if (ShareDialog.canShow(SharePhotoContent.class)) {
            Bitmap image = bitmap;
            SharePhoto photo = new SharePhoto.Builder()
                    .setBitmap(image)
// Hashtag Still not working for some reason
//                            .setShareHashtag(new ShareHashtag.Builder()
//                                    .setHashtag("#ConnectTheWorld")
//                                    .build());
                    .build();
            SharePhotoContent content = new SharePhotoContent.Builder()
                    .addPhoto(photo)
                    .build();
            shareDialog.show(content);
            shareDialog.registerCallback(mCallbackManager, new FacebookCallback<Sharer.Result>() {
                @Override
                public void onSuccess(Sharer.Result result) {
                    mFragment.postFinish(true);
                }

                @Override
                public void onCancel() {
                    mFragment.postFinish(false);
                }

                @Override
                public void onError(FacebookException error) {
                    mFragment.postFinish(false);
                }
            });

        }
    }

    @Override
    public void onLoginCallback(int requestCode, int resultCode, Intent data) {
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPostCallback(int requestCode, int resultCode, Intent data) {
    }

    private FacebookCallback<LoginResult> mFacebookLoginCallback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            Iterator<String> iterator =
                    loginResult.getRecentlyGrantedPermissions().iterator();

            boolean hasPublishPermissions = false;

            while (iterator.hasNext()) {
                String s = iterator.next();
                if (s.equalsIgnoreCase("publish_actions")) {
                    hasPublishPermissions = true;
                }
            }

            if (!hasPublishPermissions) {
                LoginManager.getInstance().logInWithPublishPermissions(mFragment.getActivity(),
                        Arrays.asList("publish_actions"));
            } else {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        mGraphCallback);
                Bundle parameters = new Bundle();
                parameters.putString("fields", "email");
                request.setParameters(parameters);
                request.executeAsync();

            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(mFragment.getActivity(), "Login Cancel",
                    Toast.LENGTH_LONG).show();
            finishLogin(false);
            LoginManager.getInstance().logOut();
            AccessToken.setCurrentAccessToken(null);
        }

        @Override
        public void onError(FacebookException exception) {
            Toast.makeText(mFragment.getActivity(), exception.getMessage(),
                    Toast.LENGTH_LONG).show();
            finishLogin(false);
            LoginManager.getInstance().logOut();
            AccessToken.setCurrentAccessToken(null);
        }
    };

    GraphRequest.GraphJSONObjectCallback mGraphCallback = new GraphRequest.GraphJSONObjectCallback() {
        private ProfileTracker mProfileTracker;

        @Override
        public void onCompleted(JSONObject object, GraphResponse response) {
            try {
                mFbEmail = object.getString("email");
                final Profile currentProfile = Profile.getCurrentProfile();
                PreferenceManager
                        .getDefaultSharedPreferences(mFragment.getActivity())
                        .edit()
                        .putString(FACEBOOK_EMAIL_PREFERENCE, mFbEmail)
                        .apply();
                mFragment.loginSuccess();

                if (currentProfile == null) {
                    // Profile not yet loaded
                    mFragment.fbInfo(null, null, mFbEmail);
                    mProfileTracker = new ProfileTracker() {
                        @Override
                        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                            finishLogin(true);
                            mFragment.fbInfo(currentProfile.getId(),
                                    currentProfile.getName(), mFbEmail);
                            Profile.setCurrentProfile(currentProfile);
                            stopTracking();
                        }
                    };
                } else {
                    mFragment.fbInfo(currentProfile.getId(),
                            currentProfile.getName(), mFbEmail);
                }
            } catch (JSONException ex) {
                mFragment.loginFailed("Could not log in to FaceBook.");
            }
        }
    };

}

I found this solution in another post...

You can use the code below in Activity and in Fragment as well. When using in Fragment make sure you pass this in ShareDialog constructor. If you pass getActivity() then onActivityResult method will not be triggered in Fragment.

and I've tried changing "mFragment.getActivity()" to "this" and "FacebookSocialSelector.this" but I get a connot resolve constructor error.

Edit: the program compiles fine if I use shareDialog(mFragment), or shareDialog(fragment), but I still do not receive the callback. I tried adding Debug Logging, but none are being triggered.

Upvotes: 1

Views: 788

Answers (1)

crymson
crymson

Reputation: 1190

I suspect that mCallbackManager is not calling onActivityResult()and therefore you won't receive any results in your registered callback to the ShareDialog. First try calling new ShareDialog(mFragment); instead of new ShareDialog(mFragment.getActivity()); Then, in your ShareFragment class (which I assume is mFragment) override onActivityResult(requestCode, resultCode, data) and do something like this:

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

Where mFacebookSocialSelector points to an instance of your FacebookSocialSelector class. Inside your FacebookSocialSelector class create a public method, like so:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}

And hopefully onSuccess will get called once you publish your post.

Upvotes: 2

Related Questions