19

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

Gopal Singh Sirvi
  • 4,539
  • 5
  • 33
  • 55
Mohammad Haque
  • 565
  • 1
  • 7
  • 16

4 Answers4

30

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);
    }
}
Golan Shay
  • 1,250
  • 18
  • 15
  • 2
    Can we get the profile picture as well using this method? (I mean by using a Request class) – ecem Feb 28 '13 at 19:13
  • 7
    I attempted to set read permissions like this : `authButton.setReadPermissions(Arrays.asList("email"));` and then tried to access the email like this `user.asMap().get("email")` but it always returns `null`. – Etienne Lawlor Aug 09 '13 at 18:40
  • 1
    see the report from Facebook [here](https://developers.facebook.com/bugs/298946933534016). – mrsus Oct 18 '13 at 14:54
  • @toobsco42 reason it retunrs null that, your given account doent give permission to provide email, try it with another account . – Mr.G Mar 06 '14 at 07:55
  • what will happen if we dont provide permission to access email address, can we ask from app itself to give email address from user – Mr.G Mar 06 '14 at 07:57
24

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.

rightparen
  • 1,693
  • 10
  • 15
  • If you use build-in LoginFragment from SDK how can you pass the extra field? – Mohammad Haque Nov 03 '12 at 13:22
  • LoginFragment also has a setReadPermissions method. – rightparen Nov 05 '12 at 17:39
  • 1
    Iam requesting emial as Session.OpenRequest openRequest = null; openRequest = new Session.OpenRequest(LoginActivity.this); if (openRequest != null) { openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS); openRequest.setPermissions(Arrays.asList("email")); mCurrentSession.openForRead(openRequest); } but I am getting null for Log.d("user email", (String) user.getProperty("email") ); – user1767260 Mar 04 '13 at 12:53
  • You are getting null because you need to make sure you set the permissions in the Facebook application in the permissions on the actual Facebook application webpage. – Jared Burrows Jun 15 '13 at 05:08
  • loginButton.setReadPermissions(Arrays.asList("email")) didn't work for me. Don't know if something else I did was the problem or this no longer works. I successfully used Golan Shay's answer. – hBrent Nov 07 '14 at 15:55
15

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
                }
            });
Volodymyr
  • 6,393
  • 4
  • 53
  • 84
  • 1
    i am searching from past few days...your answer helped me thanx – madhu527 Apr 24 '15 at 05:51
  • 1
    @vovaxo I am new to Android FB integration. Once this is done, where do I get the email of the user? – Tejas Sherdiwala May 26 '15 at 11:32
  • 2
    @Teju there is interface that you should implement `Session.StatusCallback`. Inside callback method: ` @Override public void call(Session session, SessionState sessionState, Exception e) { if (sessionState.isOpened() && session.isOpened()) { Request me = Request.newMeRequest(session, new Request.GraphUserCallback() { @Override public void onCompleted(GraphUser graphUser, Response response) { String email = graphUser.asMap().get("email").toString(); } }); me.executeAsync(); } }` – Volodymyr May 26 '15 at 14:59
  • this doesnt return email for some accounts , while other similar apps are working with same account with Facebook login, strange, any clue ? – vishal dharankar Jan 24 '16 at 09:04
1

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;
            }
        };
Mohammad Haque
  • 565
  • 1
  • 7
  • 16