19
votes

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

4
you must specify the sdk version instead of mentioning 'new Facebook android sdk', I guessNarendra Singh

4 Answers

30
votes

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);
    }
}
24
votes

When you open the Session, try including "email" in the list of permissions.

If you are using LoginButton, do something like:

loginButton.setReadPermissions(Arrays.asList("email"));

If you are opening the Session yourself, do something like:

session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList("email")));

You can experiment with requests/permissions using: https://developers.facebook.com/tools/explorer/

Once you have logged in successfully with these permissions, then try the request again including the email field.

15
votes

If you are using com.facebook.widget.LoginButton you should set permissions to this fragment, after that facebook returns email. Here is working code:

LoginButton authButton = findViewById(R.id.sign_in_facebook);
    List<String> permissions = new ArrayList<>();
    permissions.add("public_profile");
    permissions.add("email");
    permissions.add("user_birthday");
    authButton.setReadPermissions(permissions);`

EDIT Facebook updated it's sdk, which facilitated the work with it. Starting from 4.x version(changelog) you can initialize sdk in diferent places where you need it and than use it in very simple way. Here is sample:

FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
CallbackManager callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject object, GraphResponse response) {
                                    String email = object.optString("email");
                                    String uid = object.optString("id");
                                    loginPresenter.loginBySocial(email, uid);
                                }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "email");
                    request.setParameters(parameters);
                    request.executeAsync();
                }

                @Override
                public void onCancel() {
                  //your code
                }

                @Override
                public void onError(FacebookException exception) {
                  //your code
                }
            });
1
votes

I found a solution: and it works

LoginFragment loginFragment = new LoginFragment() {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View v = super.onCreateView(inflater, container, savedInstanceState);
                setReadPermissions(Arrays.asList("email"));
                return v;
            }
        };