Facebook Profile.getCurrentProfile() is always returns null after the first login

混江龙づ霸主 提交于 2019-12-08 02:44:45

问题


For the first time when I login into the app through Facebook, I'm getting profile from Profile.getCurrentProfile();

Where as when I exit the app and launch again, It was already logged in. So I can call directly Profile.getCurrentProfile(); is returning null.

Code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_page);
    Profile profile = Profile.getCurrentProfile();
    // For the first launch the profile will be null
    displayProfileName(profile);
    LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.setReadPermissions("public_profile");
    callbackManager = CallbackManager.Factory.create();
    loginButton.registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(final LoginResult loginResult) {
                    profileTracker = new ProfileTracker() {

                        @Override
                        protected void onCurrentProfileChanged(
                                Profile oldProfile, Profile currentProfile) {
                            profileTracker.stopTracking();
                            Profile.setCurrentProfile(currentProfile);
                            Profile profile = Profile.getCurrentProfile();
                            displayProfileName(profile);
                        }
                    };
                    profileTracker.startTracking();
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onError(FacebookException exception) {
                }
            });
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (profileTracker != null) {
        profileTracker.stopTracking();
    }
}

@Override
protected void onPause() {
    super.onPause();
    // Logs 'app deactivate' App Event.
    AppEventsLogger.deactivateApp(this);
}

@Override
protected void onRestart() {
    super.onRestart();
    AppEventsLogger.activateApp(this);
}
/**
*
* Method to display the Profile Name 
*/
private void displayProfileName(Profile profile) {
    if (profile != null) {
        Toast.makeText(MainActivity.this, profile.getName(),
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(MainActivity.this, "No Profile", Toast.LENGTH_LONG)
                .show();
    }
}


@Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
    super.onActivityResult(arg0, arg1, arg2);
    callbackManager.onActivityResult(arg0, arg1, arg2);
}

回答1:


There are two cases in this:

  1. For first login, follow my other answer.
  2. For second login, you will need to refresh your AccessToken and then fetch the profile. Refreshing token code can be found in this answer but the code below has it (for simplification).

The code is taken from FB's dreadful documentation).

You can put this code straight into your app, where the comment says "case 1", just invoke your normal FB login.

private AccessTokenTracker mAccessTokenTracker;

private void loginToMyFbApp() {
    FacebookSdk.sdkInitialize(this);
    if (AccessToken.getCurrentAccessToken() != null) {
        mAccessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                mAccessTokenTracker.stopTracking();
                if(currentAccessToken == null) {
                    //(the user has revoked your permissions -
                    //by going to his settings and deleted your app)
                    //do the simple login to FaceBook
                    //case 1
                }
                else {
                    //you've got the new access token now.
                    //AccessToken.getToken() could be same for both
                    //parameters but you should only use "currentAccessToken"
                    //case 2
                    fetchProfile();
                }
            }
        };
        mAccessTokenTracker.startTracking();
        AccessToken.refreshCurrentAccessTokenAsync();
    }
    else {
        //do the simple login to FaceBook
        //case 1
    }
}

private void fetchProfile() {
    GraphRequest request = GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    // this is where you should have the profile
                    Log.v("fetched info", object.toString());
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,link"); //write the fields you need
    request.setParameters(parameters);
    request.executeAsync();
}



回答2:


Instead of accessing Profile.getCurrentProfile()

use access token and make graph request in onSuccess()

( It worked for me)

here snippet of code :

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

        Log.v("profile track", (DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(loginResult.getAccessToken().getExpires())));
        GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        try {

                            String name = object.getString("name");
                            String email = object.getString("email");
                            String id = object.getString("id");
                            Toast.makeText(Login.this, name + " " + " " + email + " " + id, Toast.LENGTH_SHORT).show();

                    /*write  your code  that is to be executed after successful login*/


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

    @Override
    public void onCancel() {
    }

    @Override
    public void onError(FacebookException e) {
    }
};



回答3:


Call LoginManager.getInstance().logOut(); once you get the profile details.



来源:https://stackoverflow.com/questions/33252401/facebook-profile-getcurrentprofile-is-always-returns-null-after-the-first-logi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!