Facebook Android SDK 4.5.0 get email address
Asked Answered
F

7

34

I'm currently creating a test application to test using the latest facebook SDK to update our existing application problem is that I need to get the email address which I know depends if the user has provided one on his account. Now the account I'm using to test provides one for sure but for unknown reason the facebook SDK only provides the user_id and the fullname of the account and nothing else. I'm confused on this since the the SDK3 and above provides more information than the updated SDK4 and I'm lost on how to get the email as all the answers I've seen so far doesn't provide the email on my end. Here's my code so far:

Login Button

@OnClick(R.id.btn_login)
    public void loginFacebook(){
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
    }

LoginManager Callback:

LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                requestUserProfile(loginResult);
            }

            @Override
            public void onCancel() {
                Toast.makeText(getBaseContext(),"Login Cancelled", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(getBaseContext(),"Problem connecting to Facebook", Toast.LENGTH_SHORT).show();
            }
        });

And the request for user profile:

public void requestUserProfile(LoginResult loginResult){
        GraphRequest.newMeRequest(
                loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject me, GraphResponse response) {
                        if (response.getError() != null) {
                            // handle error
                        } else {
                            try {
                                String email = response.getJSONObject().get("email").toString();
                                Log.e("Result", email);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String id = me.optString("id");
                            // send email and id to your web server
                            Log.e("Result1", response.getRawResponse());
                            Log.e("Result", me.toString());
                        }
                    }
                }).executeAsync();
    }

The JSON response returns only the ID and full name of my account but doesn't include the email. Did I missed out something?

Fowlkes answered 25/8, 2015 at 6:10 Comment(1)
I am using same code and its work for me before some time but right now its not working can you please post complete code . callback is not calledBriard
I
106

You need to ask for parameters to facebook in order to get your data. Here I post my function where I get the facebook data. The key is in this line:

parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // Parámetros que pedimos a facebook

btnLoginFb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

        @Override
        public void onSuccess(LoginResult loginResult) {

            System.out.println("onSuccess");
            progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setMessage("Procesando datos...");
            progressDialog.show();
            String accessToken = loginResult.getAccessToken().getToken();
            Log.i("accessToken", accessToken);

            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {

                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.i("LoginActivity", response.toString());
                    // Get facebook data from login
                    Bundle bFacebookData = getFacebookData(object); 
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // Parámetros que pedimos a facebook
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
            System.out.println("onCancel");
        }

        @Override
        public void onError(FacebookException exception) {
            System.out.println("onError");
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });



private Bundle getFacebookData(JSONObject object) {

        try {
            Bundle bundle = new Bundle();
            String id = object.getString("id");

            try {
                URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=150");
                Log.i("profile_pic", profile_pic + "");
                bundle.putString("profile_pic", profile_pic.toString());

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            }

            bundle.putString("idFacebook", id);
            if (object.has("first_name"))
                bundle.putString("first_name", object.getString("first_name"));
            if (object.has("last_name"))
                bundle.putString("last_name", object.getString("last_name"));
            if (object.has("email"))
                bundle.putString("email", object.getString("email"));
            if (object.has("gender"))
                bundle.putString("gender", object.getString("gender"));
            if (object.has("birthday"))
                bundle.putString("birthday", object.getString("birthday"));
            if (object.has("location"))
                bundle.putString("location", object.getJSONObject("location").getString("name"));

            return bundle;
        }
      catch(JSONException e) {
        Log.d(TAG,"Error parsing JSON");
      }
    return null;
}
Incogitant answered 25/8, 2015 at 6:31 Comment(8)
I had to add btnLoginFb.setReadPermissions(Arrays.asList("email")); just before btnLoginFb.registerCallback(...);Flush
Glad to help you all :)Outandout
Been struggling since hours...There are several answers on stackoverflow where they haven't done the parameters part. Thanks a lot.Hachure
Is there an option for a "mobile number" in the parameters? Or could any one point out the list of supported parameters? Unable to find it.Emptor
@JigneshShah as far as I know i think facebook removed this permission due to user's privacityOutandout
Nice answer...not a whole lot out there covering the LoginManager route. All about Bundle of parameters on the 'me' request: parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location");Cori
You have a catch block missing there for the outermost try block. So those fund of copying and pasting directly, make sure you add the JSON exception catch block else you get errors in your code and come complaining without properly checking.Thicket
after trying many other solutions this is the only one that worked, I was able to retrieve email address while other methods returned null.Asteriated
A
3

Instead of getting the value of the graphResponse, access the email using the JSONObject me

userEmail = jsonObject.getString("email");
Anaconda answered 25/8, 2015 at 6:22 Comment(1)
I've also tried it before but didn't work. What I've missed is the parameters that is needed before executing the request.Fowlkes
K
3

Hope it helps you

/*** setupFacebook stuff like make login with facebook and get the userId,Name and Email*/
    private void setupFacebookStuff() {
        Log.e(TAG, "key hash= " + Utils.getKeyHash(SplashActivity.this, getPackageName()));

        // This should normally be on your application class
        FacebookSdk.sdkInitialize(SplashActivity.this);

        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                   currentAccessToken.getToken();
            }
        };

        loginManager = LoginManager.getInstance();
        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                preference.setUserLogin(true);

                final GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        try {
                                Log.e("id", "" + object);

                            if (object.has(getString(R.string.fbParamId))) {

                                final String userId = object.optString(getString(R.string.fbParamId));
                                final String userPicture = "https://graph.facebook.com/" + object.optString(getString(R.string.fbParamId)) + "/picture?type=large";

                                preference.setUserId(userId);
                                preference.setUserPictureUrl(userPicture);

                            }
                            if (object.has(getString(R.string.fbParamUserName))) {


                                final String userName = object.optString(getString(R.string.fbParamUserName));
                                preference.setUserName(userName);
                            }

                            if (object.has(getString(R.string.fbParamEmail))) {

                                final String userEmail = object.optString(getString(R.string.fbParamEmail));
                                preference.setUserName(userEmail);
                                Log.e("useremail", userEmail);
                            }

                            callMainActivity(true);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                final Bundle parameters = new Bundle();
                parameters.putString("fields", "name,email,id");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getBaseContext(), "Login Cancelled", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(getBaseContext(), "Problem connecting to Facebook", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Facebook login error " + error);
            }
        });
    }
Kalynkam answered 6/1, 2017 at 11:53 Comment(1)
"email" is better than getString(R.string.fbParamEmail).Barbarian
C
1

You can also use GraphResponse object to get the values

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) {
                            Log.v("LoginActivity", response.toString());
                            try {
                                // Application code
                                String email = response.getJSONObject().getString("email");
                                txtStatus.setText("Login Success \n" + email);
                            }catch(Exception e){
                                e.printStackTrace();;
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel()
        {
            txtStatus.setText("==============Login Cancelled=============");
        }

        @Override
        public void onError(FacebookException exception)
        {
            txtStatus.setText("==============Login Error=================");
            exception.printStackTrace();
        }
    });
Contracted answered 3/7, 2017 at 14:20 Comment(0)
T
1

Putting this code:

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

before

RegisterCallback

should solve the problem.

Tinct answered 12/7, 2017 at 7:8 Comment(0)
O
1

I guess getting email permissions can help..

LoginManager.getInstance().logInWithReadPermissions(
fragmentOrActivity,
Arrays.asList("email"));
Officer answered 18/10, 2017 at 13:18 Comment(0)
P
1

Information

If you are giving any permission to get an email address. then, Facebook can not every time gives you email address or some other details.

When, Facebook user is not signup with his email-address then Facebook can't provide you his email address.

If user is login with Facebook using email address then Facebook will provides email to you.

Facebook SDK provide only public details.

check a login with Facebook using email-address and also with phone number through.

Primrose answered 22/6, 2018 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.