Android Facebook SDK 3.2 Getting Profile Email information Showing Null

565 views Asked by At

I am using Facebook SDK 3.2 for login in my android app.

Login, logout functions working fine.

My Problem:

after login want to retrieve the Facebook Username and Email.

Username Showing Perfectly Email is not Showing.

Please help me to solve it.

MainActivity.java

  public class MainActivity extends FragmentActivity {
        String TAG="MainActivity";
        private static final String PERMISSION = "publish_actions";

        //private static final String PERMISSION = "email";

        private final String PENDING_ACTION_BUNDLE_KEY = "pending_action";

        private Button postStatusUpdateButton;
        private LoginButton loginButton;
        private ProfilePictureView profilePictureView;
        private TextView greeting;
        private PendingAction pendingAction = PendingAction.NONE;
        private GraphUser user;
        private GraphPlace place;
        private List<GraphUser> tags;
        private boolean canPresentShareDialog;

        Button LogoutButton,Pro;

    /*  private static final List<String> PERMISSION = Arrays.asList(
                "email","publish_actions");*/


        private enum PendingAction
        {
            NONE, POST_STATUS_UPDATE
        }

        private UiLifecycleHelper uiHelper;

        private Session.StatusCallback callback = new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState state,
                    Exception exception) 
            {
                onSessionStateChange(session, state, exception);
            }
        };

        private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
            @Override
            public void onError(FacebookDialog.PendingCall pendingCall,
                    Exception error, Bundle data) {
                Log.d(TAG, String.format("Error: %s", error.toString()));
            }

            @Override
            public void onComplete(FacebookDialog.PendingCall pendingCall,
                    Bundle data) {
                Log.d(TAG, "Success!");
            }
        };



        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            uiHelper = new UiLifecycleHelper(this, callback);
            uiHelper.onCreate(savedInstanceState);
            // Can we present the share dialog for regular links?
            canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

            if (savedInstanceState != null) {
                String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
                pendingAction = PendingAction.valueOf(name);
            }

            setContentView(R.layout.activity_main);



            loginButton = (LoginButton) findViewById(R.id.login_button);
            loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() 
            {
                        @Override
                        public void onUserInfoFetched(GraphUser user) 
                        {
                            MainActivity.this.user = user;
                            updateUI();
                            // It's possible that we were waiting for this.user to
                            // be populated in order to post a status update.
                            handlePendingAction();


                        }
                    });

            profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
            greeting = (TextView) findViewById(R.id.greeting);

            postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
            postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    performPublish(PendingAction.POST_STATUS_UPDATE,canPresentShareDialog);
                }
            });

              LogoutButton=(Button)findViewById(R.id.LogoutButton);
              LogoutButton.setOnClickListener(new View.OnClickListener() 
              {

                @Override
                public void onClick(View v)
                {

                    //callFacebookLogout(session);
                    Logout();

                }
            });

        }



        //override lifecycle methods so that UiLifecycleHelper know about state of the activity
        @Override
        protected void onResume() {
            super.onResume();
            uiHelper.onResume();
            updateUI();
        }

        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            uiHelper.onSaveInstanceState(outState);
            outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
        }

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

        @Override
        public void onPause() {
            super.onPause();
            uiHelper.onPause();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            uiHelper.onDestroy();
        }

        private void onSessionStateChange(Session session, SessionState state,Exception exception) 
        {
            if (state.isOpened()) {
                Toast.makeText(getApplicationContext(), "User logged in...", Toast.LENGTH_SHORT).show();

                getUserData(session,state);



            } else if (state.isClosed()) {
                Toast.makeText(getApplicationContext(), "User logged out...", Toast.LENGTH_SHORT).show();
            }
            if (pendingAction != PendingAction.NONE
                    && (exception instanceof FacebookOperationCanceledException 
                    || exception instanceof FacebookAuthorizationException)) {
                new AlertDialog.Builder(MainActivity.this)//if permission is not granted
                        .setTitle(R.string.cancelled)
                        .setMessage(R.string.permission_not_granted)
                        .setPositiveButton(R.string.ok, null).show();
                pendingAction = PendingAction.NONE;
            } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
                handlePendingAction();
            }
            updateUI();
        }

        private void updateUI() 
        {
            Session session = Session.getActiveSession();
            boolean enableButtons = (session != null && session.isOpened());

            postStatusUpdateButton.setEnabled(enableButtons
                    || canPresentShareDialog);

            if (enableButtons && user != null) 
            {
                profilePictureView.setProfileId(user.getId());
                greeting.setText(getString(R.string.hello_user, user.getFirstName()));



            } else {
                profilePictureView.setProfileId(null);
                greeting.setText(null);
            }


        }

        @SuppressWarnings("incomplete-switch")
        private void handlePendingAction() {
            PendingAction previouslyPendingAction = pendingAction;
            // These actions may re-set pendingAction if they are still pending, but we assume they
            // will succeed.
            pendingAction = PendingAction.NONE;

            switch (previouslyPendingAction) {
            case POST_STATUS_UPDATE:
                postStatusUpdate();
                break;
            }
        }

        private interface GraphObjectWithId extends GraphObject {
            String getId();
        }

        private void showPublishResult(String message, GraphObject result,
                FacebookRequestError error) {
            String title = null;
            String alertMessage = null;
            if (error == null) {
                title = getString(R.string.success);
                String id = result.cast(GraphObjectWithId.class).getId();
                alertMessage = getString(R.string.successfully_posted_post,
                        message, id);
            } else {
                title = getString(R.string.error);
                alertMessage = error.getErrorMessage();
            }

            new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
                    .setPositiveButton(R.string.ok, null).show();
        }

        // create sample post to update on facebook
        private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
            return new FacebookDialog.ShareDialogBuilder(this)
                    .setName("Hello Facebook")
                    .setDescription("this is sample post from androidSRC.net to demonstrate facebook login in your android application")
                    .setLink("http://androidsrc.net/");
        }

        private void postStatusUpdate() {
            if (canPresentShareDialog) {
                FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
                uiHelper.trackPendingDialogCall(shareDialog.present());
            } else if (user != null && hasPublishPermission()) {
                final String message = getString(R.string.status_update,
                        user.getFirstName(), (new Date().toString()));
                Request request = Request.newStatusUpdateRequest(
                        Session.getActiveSession(), message, place, tags,
                        new Request.Callback() {
                            @Override
                            public void onCompleted(Response response) {
                                showPublishResult(message,
                                        response.getGraphObject(),
                                        response.getError());
                            }
                        });
                request.executeAsync();
            } else {
                pendingAction = PendingAction.POST_STATUS_UPDATE;
            }
        }

        //check if app has permission to publish on facebook
        private boolean hasPublishPermission() {
            Session session = Session.getActiveSession();
            return session != null && session.getPermissions().contains("publish_actions")&&session.getPermissions().contains("email");
        }

        private void performPublish(PendingAction action, boolean allowNoSession) {
            Session session = Session.getActiveSession();
            if (session != null) {
                pendingAction = action;
                if (hasPublishPermission()) {
                    // We can do the action right away.
                    handlePendingAction();
                    return;
                } else if (session.isOpened()) {
                    // We need to get new permissions, then complete the action when
                    // we get called back.
                    session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
                            this, PERMISSION));
                    return;
                }
            }

            if (allowNoSession) {
                pendingAction = action;
                handlePendingAction();
            }
        }

        public void Logout()
        {
            if (Session.getActiveSession() != null) 
            {
                Session.getActiveSession().closeAndClearTokenInformation();
                Toast.makeText(getApplicationContext(), "logged out...", Toast.LENGTH_SHORT).show();
            }

            Session.setActiveSession(null);
        }




        private void getUserData(Session session, SessionState state)
        {
            if (state.isOpened())
            {
                Request.newMeRequest(session, new Request.GraphUserCallback()
                {
                    @Override
                    public void onCompleted(GraphUser user, Response response)
                    {
                        if (response != null)
                        {
                            try
                            {
                                String name = user.getName();
                                // If you asked for email permission
                                String email = (String) user.getProperty("email");
                               // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                                Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                                //Log.d(LOG_TAG, "Exception e");
                            }

                        }
                    }
                }).executeAsync();
            }
        }

method for getting the User data from Facebook, after Logged in

  private void getUserData(Session session, SessionState state)
        {
            if (state.isOpened())
            {
                Request.newMeRequest(session, new Request.GraphUserCallback()
                {
                    @Override
                    public void onCompleted(GraphUser user, Response response)
                    {
                        if (response != null)
                        {
                            try
                            {
                                String name = user.getName();
                                // If you asked for email permission
                                String email = (String) user.getProperty("email");
                               // Log.e(LOG_TAG, "Name: " + name + " Email: " + email);

                                Toast.makeText(getApplicationContext(), "Name: " + name + " Email: " + email, Toast.LENGTH_SHORT).show();
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                                //Log.d(LOG_TAG, "Exception e");
                            }

                        }
                    }
                }).executeAsync();
            }
        }
1

There are 1 answers

0
Kumar On BEST ANSWER

I found the Solution for my Question

I have Missed the Permission for getting the facebook Profile email in My code

added the permission below my login button inside oncreate method

loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email","user_photos")); 

Now its working fine