Android Facebook 4.0 SDK如何获取电子邮件,用户的出生日期和性别


144

我正在使用以下代码。我想要用户的出生日期,电子邮件和性别。请帮忙。如何检索这些数据?

这是我onViewCreated()里面的碎片。

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

}

这是我的回调方法。

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


嗨,@ Sriyank,如果您解决了问题,请帮助我。登录完成后,我想从Facebook登录片段中获取用户信息。要进行下一个活动,请告诉我该怎么做?
Devendra Singh

下面的解决方案,但要小心,因为如果用户通过其电话号码登录,则电子邮件可能为空。请访问stackoverflow.com/questions/29517667/…stackoverflow.com/questions/29493486/…–
pegaltier

Answers:


335

这不是设置权限的正确方法,因为每个方法调用都将覆盖它们。

替换为:

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

使用以下方法作为方法setReadPermissions()接受ArrayList:

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

这也是如何查询额外数据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());
        }
    });
}

编辑:

一个可能的问题是Facebook认为您的电子邮件无效。要对其进行测试,请使用Graph API Explorer并尝试获取它。如果您仍然收不到电子邮件,请在个人资料设置中进行更改,然后重试。对于一些开发人员来说,这种方法解决了这个问题。


2
嘿@Schwertfisch,您可以演示如何使用object.getString(“ email”); ,这对我非常有帮助:)
Ajeet 2015年

3
为什么已经设置了“为什么电子邮件没有价值”错误loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
stackex

1
@Schwertfisch,就我而言,即使使用Graph API Explorer也无法收到电子邮件,因此我向帐户添加了替代电子邮件,并且该电子邮件有效,也许您的电子邮件无效。
卡扬·阿尔梅达

1
@DevendraSingh,您可以获取这些值并将其放入一个额外的Intent中。在第二个活动中,Bundle extras = getIntent()。getExtras();。if(extras!= null){email = extras.getString(“ email”); 您也可以拥有一个静态变量并分配值。对不起我的英语不好。我不知道这是否是您想要的答案
schwertfisch 2015年

85
我只想说Facebook文档太差劲了!很遗憾,我们需要在这里了解如何进行操作。
2015年

13

使用此代码段获取所有个人资料信息

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) {

        }
    };

12

您不会在onSuccess()需要实现ProfileTracker回调和注册回调的情况下获得Profile

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

另外,不要忘记处理配置文件跟踪器的启动和停止

现在,您将拥有一个配置文件以从中获取AccessToken(解决了空配置文件的问题)。您只需要使用“ https://developers.facebook.com/docs/android/graph#userdata ”即可获取任何数据。


1
但是,获取电子邮件的性别和性别的语法是什么?u能请告诉我
Sriyank悉达多

2
我将其作为访问令牌:{AccessToken令牌:ACCESS_TOKEN_REMOVED权限:[user_friends,电子邮件,user_birthday,basic_info]}我正在FacebookCallBack下使用此代码---- AccessToken mAccessToken = loginResult.getAccessToken(); 你能告诉我这是什么意思吗?以及如何解决此错误并获取访问令牌?
Sriyank Siddhartha 2015年

@SriyankSiddhartha您对此有任何解决方案吗?您可以在此处更新,是否遇到相同的问题
Prabha1 2015年

@Sriyank,我也面临同样的问题,无法获取电子邮件ID。如果您找到任何解决方案,请帮助我。提前致谢。
Ramesh 2015年

我仍然找不到任何解决方案...我目前仍在使用旧的SDK。.请让我知道您是否获得解决方案..谢谢
Sriyank Siddhartha 2015年

8

登录后

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


2

这对我有用,希望能帮助到别人(使用我自己的按钮而不是FB登录按钮)

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

2

以下是查找电子邮件ID,名称和个人资料网址等的代码

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

2

这是一个可行的解决方案(2019):将这段代码放入您的登录逻辑中;

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

0

在单击按钮上添加此行

loginButton.setReadPermissions(Arrays.asList(“ public_profile”,“电子邮件”,“ user_birthday”,“ user_friends”)));


-3

使用Profile类的FB静态方法getCurrentProfile()检索那些信息。

 Profile profile = Profile.getCurrentProfile();
 String firstName = profile.getFirstName());
 System.out.println(profile.getProfilePictureUri(20,20));
 System.out.println(profile.getLinkUri());

39
问题是关于电子邮件,生日和性别。这不能解决任何问题。
Siamaster

2
这并没有给电子邮件
维沙尔dharankar
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.