151

I am using the following code. I want the user's Date Of Birth, Email and Gender. Please help. How to retrieve those data?

This is my onViewCreated() inside the Fragment.

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    // Setup TextView.
    mTextDetails = (TextView) view.findViewById(R.id.text_details);

    // Set up Login Button.
    LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
    // setFragment only if you are using it inside a Fragment.
    mButtonLogin.setFragment(this);
    mButtonLogin.setReadPermissions("user_friends");
    mButtonLogin.setReadPermissions("public_profile");
    mButtonLogin.setReadPermissions("email");
    mButtonLogin.setReadPermissions("user_birthday");

    // Register a callback method when Login Button is Clicked.
    mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);

}

This is my Callback Method.

private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Log.d("Shreks Fragment", "onSuccess");


        Profile profile = Profile.getCurrentProfile();
        Log.d("Shreks Fragment onSuccess", "" +profile);

        // Get User Name
        mTextDetails.setText(profile.getName() + "");

    }


    @Override
    public void onCancel() {
        Log.d("Shreks Fragmnt", "onCancel");
    }

    @Override
    public void onError(FacebookException e) {
        Log.d("Shreks Fragment", "onError " + e);
    }
};
Gopal Singh Sirvi
  • 4,539
  • 5
  • 33
  • 55
Sriyank Siddhartha
  • 1,832
  • 2
  • 12
  • 8
  • 1
    https://developers.facebook.com/docs/android/graph#userdata-step3 – binary Mar 29 '15 at 10:04
  • Hi, @Sriyank please help me if you resolved your issue. i want to get the user info from facebook signin fragment after login completed want to go next activity please tell me how can i do that? – Devendra Singh Jun 26 '15 at 08:40
  • the solution below but be careful because the email may be empty if the user is logged via his phone number Visit http://stackoverflow.com/questions/29517667/android-facebook-sdk-4-x-how-to-get-email-address-and-facebook-access-token-to and http://stackoverflow.com/questions/29493486/create-a-request-in-facebook-sdk-4-android – pegaltier Oct 07 '15 at 20:42

9 Answers9

345

That's not the right way to set the permissions as you are overwriting them with each method call.

Replace this:

mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.setReadPermissions("public_profile");
mButtonLogin.setReadPermissions("email");
mButtonLogin.setReadPermissions("user_birthday");

With the following, as the method setReadPermissions() accepts an ArrayList:

loginButton.setReadPermissions(Arrays.asList(
        "public_profile", "email", "user_birthday", "user_friends"));

Also here is how to query extra data GraphRequest:

private LoginButton loginButton;
private CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setReadPermissions(Arrays.asList(
            "public_profile", "email", "user_birthday", "user_friends"));

    callbackManager = CallbackManager.Factory.create();

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("LoginActivity", response.toString());

                            // Application code
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); // 01/31/1980 format
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            // App code
            Log.v("LoginActivity", "cancel");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.v("LoginActivity", exception.getCause().toString());
        }
    });
}

EDIT:

One possible problem is that Facebook assumes that your email is invalid. To test it, use the Graph API Explorer and try to get it. If even there you can't get your email, change it in your profile settings and try again. This approach resolved this issue for some developers commenting my answer.

Paul Lammertsma
  • 37,593
  • 16
  • 136
  • 187
schwertfisch
  • 4,549
  • 1
  • 19
  • 32
  • 2
    Hey @Schwertfisch can you show how to use object.getString("email"); ,it would be very helpful for me :) – Ajeet Apr 16 '15 at 05:47
  • @Ajeet same way, String email = ""; try{ email = object.getString("email"); }catch (JSONException exe){ //handle Json exception } – schwertfisch Apr 16 '15 at 15:51
  • 3
    why do I get "No value for email" error despite I already set `loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));`? – stackex Apr 20 '15 at 09:20
  • @stackex try debbuging the data, there are two callback objects, graphresponse and jsonobject, try this, String raw = graphresponse.getRawResponse(); the information string and also you can see something like this in graphobject {"id":"2312312321312312","email":"email@msn.com","name":"Pepito"} – schwertfisch Apr 21 '15 at 14:45
  • I use `Bundle parameters = new Bundle(); parameters.putString("fields", "id, email"); facebookRequest.setParameters(parameters);` so I expect the return will be id and email, right? What I got when I print jsonObject and graphResponse is `{"id":"xxxxxxxxxxxxxxxxxxxxxx"}`. I've checked my account permission, email is checked already. – stackex Apr 22 '15 at 01:40
  • @stackex it's extrange. maybe you can try other way. with LoginManager (Without LoginButton). Check FB developers documentation. Maybe it works for you. – schwertfisch Apr 22 '15 at 14:49
  • @Sriyank : Did you find solution for this problem, Please help me i'm facing the same issue. – Ramesh Apr 24 '15 at 15:02
  • you can put loginButton.setReadPermissions("public_profile", "emai"l, "user_birthday","user_friends"); instead of loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends")); – Jachumbelechao Unto Mantekilla Apr 28 '15 at 19:41
  • still facing same issue here with the email. When I login onto facebook, I only have email in the setReadPermissions, when I check the token, under the permissions, only public profile is checked. – CularBytes May 17 '15 at 18:07
  • Maybe it's not an issue, I have tried changing the app permissions after was granted in configuration>Apps>some app and i can't get the user information. – schwertfisch May 18 '15 at 15:06
  • 1
    @Schwertfisch in my case, I couldn't get my email even using Graph API Explorer, so I added an alternative email to my account and it worked, maybe your email is invalid. – Kayan Almeida May 20 '15 at 20:13
  • @KayanAlmeida :-D it's ok – schwertfisch May 20 '15 at 20:17
  • @KayanAlmeida wow, finally I solve my issue. your solution works. I need to add additional email to my account. I don't know why, but it finally appears when I request it. :D – stackex Jun 15 '15 at 09:53
  • @Schwertfisch Maybe you should edit your answer with this info, it really saves a lot of time! =) – Kayan Almeida Jun 15 '15 at 14:57
  • @KayanAlmeida I don't write a good english explaining, can you do it please and i aprove it. – schwertfisch Jun 15 '15 at 15:03
  • @Schwertfisch Done, and reading your answer it's clear to me that you write very good answers! Feel free to change my edit! – Kayan Almeida Jun 15 '15 at 15:12
  • @Schwertfisch how can i fire an intent with these datas, as i want to go on next activity with the object that containing the user data. – Devendra Singh Jun 26 '15 at 08:05
  • 1
    @DevendraSingh you have yo get the values and put them in a extra, Intent myIntent = new Intent(this, SecondActivity.class);myIntent.putExtra("email", object.getString("email"));..... In the second activity Bundle extras = getIntent().getExtras(); if(extras != null){ email = extras.getString("email"); } Also you can have a static variable and assign the value. Sorry for my english. I don't know if this is the answer that you want – schwertfisch Jun 26 '15 at 21:36
  • 90
    I just have to say That Facebook Docs are so poor! it is a shame we need to find out how to do it here. – Gal Rom Jul 20 '15 at 06:46
  • No comments were as clear, you should add an email to the app settings so that Facebook can contact you , thats contact email. Also if you want access to email from other accounts make it public. – vishal dharankar Oct 29 '15 at 10:08
  • Thank you thank you thank you so much for edit and Give link for Graph API Explorer https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Did%2Cname%2Cemail& – GreenROBO Nov 03 '15 at 10:37
  • I think "If even there you can't get your email, change it in your profile settings and try again" this approach helps me but i am not able to understand where to edit profile in google account or Facebook account profile. please help me i have stucked from few hours – Rahul Chaudhary Jan 14 '16 at 13:26
  • This is exactly what I am doing but my response in the graphapi is as follows {Response: responseCode: 400, graphObject: null, error: {HttpStatus: 400, errorCode: 190, errorType: OAuthException, errorMessage: Invalid OAuth access token.} --- am I missing something, loginResult.getAccessToken() is what I am using – Lion789 Feb 24 '16 at 04:52
  • I can't get email. my json request is like this : {"name":"my name","id":"my id"} – serabile Apr 09 '16 at 11:31
  • I've used the same code, but still the callback method is not at all initiated. Can you please tell why it is??? I've have posted my code in the following link http://stackoverflow.com/questions/37009457/facebook-registercallback-method-not-initiated – Parthiban M May 04 '16 at 06:48
  • @ParthibanM I just answered your questions, sorry for the delay – schwertfisch May 04 '16 at 14:27
  • 1
  • 1
    Email can be empty even if you request the email permission it is not guaranteed you will get an email address. For example, if someone signed up for Facebook with a phone number instead of an email address (Link: https://developers.facebook.com/docs/facebook-login/permissions/v3.0#reference-email) – Nguyen Tan Dat May 22 '18 at 07:11
12

You won't get Profile in onSuccess() you need to implement ProfileTracker along with registering callback

mProfileTracker = new ProfileTracker() {
    @Override
    protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
        // Fetch user details from New Profile
    }
};

Also don't forget to handle the start and stop of profile tracker

Now you will have a profile to get AccessToken from (solved the issue of null profile). You just have to use "https://developers.facebook.com/docs/android/graph#userdata" to get any data.

Ankit Bansal
  • 1,801
  • 17
  • 34
  • 1
    But what is the syntax to get the email dob and gender? can u please tell me – Sriyank Siddhartha Mar 29 '15 at 04:15
  • 2
    I am getting this as a Access token : {AccessToken token:ACCESS_TOKEN_REMOVED permissions:[user_friends, email, user_birthday, basic_info]} I am using this code under FacebookCallBack ---- AccessToken mAccessToken = loginResult.getAccessToken(); Can you please tell me what does it means? and how to resolve this error and get Access token? – Sriyank Siddhartha Mar 30 '15 at 11:34
  • @SriyankSiddhartha Do you got any solution for this ?Could you update here ,Facing same issue – Prabha1 Apr 24 '15 at 12:05
  • @Sriyank, i'm facing the same issue too, not able to get email id. please help me if you find any solutions. thanks in advance. – Ramesh Apr 24 '15 at 15:07
  • I am still not able to find any solution... I am currently still using old sdk.. please let me know if u get the solution.. thankyou – Sriyank Siddhartha Apr 27 '15 at 07:07
11

After Login

private void getFbInfo() {
    GraphRequest request = GraphRequest.newMeRequest(
            AccessToken.getCurrentAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(
                        JSONObject object,
                        GraphResponse response) {
                    try {
                        Log.d(LOG_TAG, "fb json object: " + object);
                        Log.d(LOG_TAG, "fb graph response: " + response);

                        String id = object.getString("id");
                        String first_name = object.getString("first_name");
                        String last_name = object.getString("last_name");
                        String gender = object.getString("gender");
                        String birthday = object.getString("birthday");
                        String image_url = "http://graph.facebook.com/" + id + "/picture?type=large";

                        String email;
                        if (object.has("email")) {
                            email = object.getString("email");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,first_name,last_name,email,gender,birthday"); // id,first_name,last_name,email,gender,birthday,cover,picture.type(large)
    request.setParameters(parameters);
    request.executeAsync();
}
Ahamadullah Saikat
  • 4,437
  • 42
  • 39
5

Following is the code to find email id, name and profile url etc

    private CallbackManager callbackManager;

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_sign_in);
//TODO on click of fb custom button call handleFBLogin()
     callbackManager = CallbackManager.Factory.create();
    }

    private void handleFBLogin() {
            AccessToken accessToken = AccessToken.getCurrentAccessToken();
            boolean isLoggedIn = accessToken != null && !accessToken.isExpired();

            if (isLoggedIn && Store.isUserExists(ActivitySignIn.this)) {
                goToHome();
                return;
            }

            LoginManager.getInstance().logInWithReadPermissions(ActivitySignIn.this, Arrays.asList("public_profile", "email"));
            LoginManager.getInstance().registerCallback(callbackManager,
                    new FacebookCallback<LoginResult>() {
                        @Override
                        public void onSuccess(final LoginResult loginResult) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setFacebookData(loginResult);
                                }
                            });
                        }

                        @Override
                        public void onCancel() {
                            Toast.makeText(ActivitySignIn.this, "CANCELED", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(FacebookException exception) {
                            Toast.makeText(ActivitySignIn.this, "ERROR" + exception.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }

private void setFacebookData(final LoginResult loginResult) {
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        // Application code
                        try {
                            Log.i("Response", response.toString());

                            String email = response.getJSONObject().getString("email");
                            String firstName = response.getJSONObject().getString("first_name");
                            String lastName = response.getJSONObject().getString("last_name");
                            String profileURL = "";
                            if (Profile.getCurrentProfile() != null) {
                                profileURL = ImageRequest.getProfilePictureUri(Profile.getCurrentProfile().getId(), 400, 400).toString();
                            }

                           //TODO put your code here
                        } catch (JSONException e) {
                            Toast.makeText(ActivitySignIn.this, R.string.error_occurred_try_again, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,email,first_name,last_name");
        request.setParameters(parameters);
        request.executeAsync();
    }
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            callbackManager.onActivityResult(requestCode, resultCode, data);
    }
aanshu
  • 1,602
  • 12
  • 13
5

Here's a working solution (2019): put this code inside your login logic;

 GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject json, GraphResponse response) {
                    // Application code
                    if (response.getError() != null) {
                        System.out.println("ERROR");
                    } else {
                        System.out.println("Success");
                        String jsonresult = String.valueOf(json);
                        System.out.println("JSON Result" + jsonresult);

                        String fbUserId = json.optString("id");
                        String fbUserFirstName = json.optString("name");
                        String fbUserEmail = json.optString("email");
                        //String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
                        Log.d("SignUpActivity", "Email: " + fbUserEmail + "\nName: " + fbUserFirstName + "\nID: " + fbUserId);
                    }
                    Log.d("SignUpActivity", response.toString());
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
            setResult(RESULT_CANCELED);
            Toast.makeText(SignUpActivity.this, "Login Attempt Cancelled", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            Toast.makeText(SignUpActivity.this, "An Error Occurred", Toast.LENGTH_LONG).show();
            error.printStackTrace();
        }
    });
Chidi
  • 189
  • 2
  • 10
3

You can use the GraphRequest class to issue calls to the Facebook Graph API to get user information. See https://developers.facebook.com/docs/android/graph for more info.

Chris Pan
  • 1,903
  • 14
  • 16
3

This is worked for me, Hope to help someone (Using my own button not FB login button )

CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_sign_in_user);



     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) {
                    try {
                        Log.i("RESAULTS : ", object.getString("email"));
                    }catch (Exception e){

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

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Log.i("RESAULTS : ", error.getMessage());
        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}


boolean isEmailValid(CharSequence email) {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

public void signupwith_facebook(View view) {

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}
Mohammed Riyadh
  • 883
  • 3
  • 11
  • 34
0

Add this line on Click on button

loginButton.setReadPermissions(Arrays.asList( "public_profile", "email", "user_birthday", "user_friends"));

adarsh
  • 403
  • 3
  • 8
-3

Use FB static method getCurrentProfile() of Profile class to retrieve those info.

 Profile profile = Profile.getCurrentProfile();
 String firstName = profile.getFirstName());
 System.out.println(profile.getProfilePictureUri(20,20));
 System.out.println(profile.getLinkUri());
Deepika
  • 516
  • 4
  • 6