Profile.getCurrentProfile() returns null after logging in (FB API v4.0)

前端 未结 4 1839
生来不讨喜
生来不讨喜 2020-12-08 06:44

For some reason Profile.getCurrentProfile() shows up null at times right after logging into FaceBook, using FB API v4.0.

This is causing problems for me

4条回答
  •  不知归路
    2020-12-08 06:58

    Like Hardy said, you have to create an instance of ProfileTracker which will start tracking profile updates, (i.e ProfileTracker.onCurrentProfileChanged() will be called when the user's profile finishes being fetched).

    Following is the complete code that you'd need to login to FB and get the user's profile:

    LoginButton loginButton = (LoginButton) findViewById(R.id.btn_facebook);
    loginButton.setReadPermissions("public_profile");
    mCallbackManager = CallbackManager.Factory.create();
    loginButton.registerCallback(mCallbackManager, new FacebookCallback() {
    
        private ProfileTracker mProfileTracker;
    
        @Override
        public void onSuccess(LoginResult loginResult) {
            if(Profile.getCurrentProfile() == null) {
                mProfileTracker = new ProfileTracker() {
                    @Override
                    protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                        Log.v("facebook - profile", currentProfile.getFirstName());
                        mProfileTracker.stopTracking();
                    }
                };
                // no need to call startTracking() on mProfileTracker
                // because it is called by its constructor, internally.
            }
            else {
                Profile profile = Profile.getCurrentProfile();
                Log.v("facebook - profile", profile.getFirstName());
            }
        }
    
        @Override
        public void onCancel() {
            Log.v("facebook - onCancel", "cancelled");
        }
    
        @Override
        public void onError(FacebookException e) {
            Log.v("facebook - onError", e.getMessage());
        }
    });
    

    You must override your Activity's or Fragment's onActivityResult() as below:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if you don't add following block,
        // your registered `FacebookCallback` won't be called
        if (mCallbackManager.onActivityResult(requestCode, resultCode, data)) {
            return;
        }
    }
    

    Edit:

    Code updated with Alex Zezekalo's suggestion to only call mProfileTracker.startTracking(); if Profile.getCurrentProfile() returns null.

提交回复
热议问题