Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

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.


Use this snippet for get all profile info

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();

            // Facebook Email address
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(
                                JSONObject object,
                                GraphResponse response) {
                            Log.v("LoginActivity Response ", response.toString());

                            try {
                                Name = object.getString("name");

                                FEmail = object.getString("email");
                                Log.v("Email = ", " " + FEmail);
                                Toast.makeText(getApplicationContext(), "Name " + Name, Toast.LENGTH_LONG).show();


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();


        }

        @Override
        public void onCancel() {
            LoginManager.getInstance().logOut();

        }

        @Override
        public void onError(FacebookException e) {

        }
    };

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.


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();
}

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