Trying to integrate Facebook Login in android app. The login and logout is working fine but sometimes even after login in, profile is still null. As soon as I get the details from Facebook I logout. I referred to some other questions on Stackoverflow, and applied it in the code but somewhere still something is going wrong and not able to figure it out.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.login_activity);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.btnFacebookSignin);
loginButton.setReadPermissions("public_profile, email");
loginButton.registerCallback(callbackManager, facebookCallback);
}
FacebookCallback<LoginResult> facebookCallback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
if(Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
Log.v("facebook - profile", profile2.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
}
else {
Profile profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
String name = profile.getName();
Uri pictureUri = profile.getProfilePictureUri(200, 200);
String email = object.optString("email");
String uid = object.optString("id");
try {
sendLogin(uid, name, email, pictureUri.toString(), "fb");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
facebookLogout();
} else {
facebookLogout();
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
Toast.makeText(getApplication(), "Something went wrong, please try again later", Toast.LENGTH_LONG).show();
}
};
public void facebookLogout() {
LoginManager.getInstance().logOut();
}