Access user email using new Facebook Android SDK

Mohammad Haque picture Mohammad Haque · Nov 3, 2012 · Viewed 30.1k times · Source

Hi I'm playing with new Facebook Android SDK. One thing I could not figure out is how can I ask for email address. I tried following but it returned values for all fields except email address. I guess I probably have to ask permission separately for email address but not sure how I can do that if I use LoginFragment.

Request request = Request.newMeRequest(session, new GraphUserCallback() {

    @Override
    public void onCompleted(GraphUser user, Response response) {
        profilePictureView.setUserId(user.getId());
        userNameView.setText(user.getName());
    }
});

String NAME = "name";
String ID = "id";
String PICTURE = "picture";
String EMAIL = "email";
String FIELDS = "fields";
String REQUEST_FIELDS = TextUtils.join(",", new String[] {
    ID, NAME, PICTURE, EMAIL
});

Bundle parameters = new Bundle();
parameters.putString(FIELDS, REQUEST_FIELDS);
request.setParameters(parameters);
Request.executeBatchAsync(request);

Any help is appreciated. Thanks

Answer

Golan Shay picture Golan Shay · Nov 12, 2012

Do the following:

After setting the permissions as above access the email via: user.asMap().get("email"));

See the example below

@Override
protected void onSessionStateChange(SessionState state, Exception exception) {

    // user has either logged in or not ...
    if (state.isOpened()) {
        // make request to the /me API
        Request request = Request.newMeRequest(this.getSession(),
                new Request.GraphUserCallback() {
                    // callback after Graph API response with user object

                    @Override
                    public void onCompleted(GraphUser user,
                            Response response) {
                        // TODO Auto-generated method stub
                        if (user != null) {
                            TextView etName = (TextView) findViewById(R.id.etName);

                            etName.setText(user.getName() + ","
                                    + user.getUsername() + ","
                                    + user.getId() + "," + user.getLink()
                                    + "," + user.getFirstName()+ user.asMap().get("email"));

                        }
                    }
                });
        Request.executeBatchAsync(request);
    }
}