Android Facebook SDK 3.2 获取配置文件电子邮件信息显示为空

Android Facebook SDK 3.2 Getting Profile Email information Showing Null

我在 android 应用程序中使用 Facebook SDK 3.2 登录。

登录、注销功能正常。

我的问题:

登录后想要检索 Facebook 用户名和电子邮件。

用户名显示完美电子邮件未显示。

请帮我解决一下

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

登录后从 Facebook 获取用户数据的方法

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

我找到了问题的解决方案

我错过了在我的代码中获取 facebook 个人资料电子邮件的权限

oncreate 方法

中的登录按钮下方添加了权限
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email","user_photos")); 

现在工作正常