how to get email id from facebook sdk in android applications?
Solution 1:
Before calling Session.openActiveSession
do this to get permissions add this:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
The last parameter in Session.openActiveSession()
should be permissions
.
Now you can access user.getProperty("email").toString()
.
EDIT:
This is the way I am doing facebook authorization:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
loginProgress.setVisibility(View.VISIBLE);
//start Facebook session
openActiveSession(this, true, new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
//make request to the /me API
Log.e("sessionopened", "true");
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String id = user.getId();
String email = user.getProperty("email").toString();
Log.e("facebookid", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
}
}
});
}
}
}, permissions);
Add this method to your activity:
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List<String> permissions) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
Solution 2:
Following the suggestion of Egor N, I change my old code
Session.openActiveSession(this, true, statusCallback);
whith this new one:
List<String> permissions = new ArrayList<String>();
permissions.add("email");
Session.openActiveSession(this, true, permissions, statusCallback);
Now FB ask the user about the permission of email and I can read it in the response.