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
Facebook loads the profile information asynchronously, so even after you get your result from the login callback, Profile.getCurrentProfile() will return null.
However, every time the user logs in through Facebook (the first time and every subsequent time) his profile will change and will fire the profiletracker. This is where you must call the profile.
Here is how you should structure your code. You must listen for the ProfileTracker to update in order to update your user properties - avoid calling getCurrentProfile outside the tracker during the login process:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile profile, Profile profile1) {
//Listen for changes to the profile or for a new profile: update your
//user data, and launch the main activity afterwards. If my user has just logged in,
//I make sure to update his information before launching the main Activity.
Log.i("FB Profile Changed", profile1.getId());
updateUserAndLaunch(LoginActivity.this);
}
};
profileTracker.startTracking();
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
//Check that the new token is valid. This tracker is fired
//when the user logs in the first time and afterwards any time he interacts with
//the Facebook API and there is a change in his permissions.
if (!accessTokenIsValid(currentAccessToken)){
Log.i("FB Token Updated", String.valueOf(currentAccessToken.getPermissions()));
requestLogin();
}
}
};
// User already has a valid access token? Then take the user to the main activity
if (accessTokenIsValid(AccessToken.getCurrentAccessToken())){
launchApp();
}else{
//Show the Facebook login page
requestLogin();
}
}
The key here is that you should not call Profile.getcurrentprofile from the login callback (either LoginManager,registercallback or loginButton.registercallback) - the values are not reliable. Set up the tracker and rely on it firing at the opportune time in order to get updated profile info.