I need user's email address after successful facebook login in android using SDK 4.0
Yeah, it worked. The only thing required was to change GraphRequest
to GraphRequestAsyncTask
in onSuccess
method of FacebookCallBack
, and then user details could easily be fetched from the JSONObject
.
@Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
final FBUser fbUser = new FBUser();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
fbUser.setEmail(user.optString("email"));
fbUser.setName(user.optString("name"));
fbUser.setId(user.optString("id"));
}
}).executeAsync();
}
FBUser Model Class
public class FBUser {
private String displayName;
private String email;
public FBUser(String displayName, String email) {
this.displayName= displayName;
this.email = email;
}
public FBUser() {
}
public String getName() {
return displayName;
}
public void setName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
In the new facebook graph you need to ask permissions for access that information. for example on the activity you have put the LoginButton you add this line in the OnCreate method
loginButtonFacebook.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday"));
Then you get that information
loginButtonFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
}
}
}).executeAsync();
}