无法从Facebook获取姓名和电子邮件

时间:2017-08-17 16:55:10

标签: android android-studio facebook-graph-api facebook-login facebook-sdk-4.0

我试图从Facebook登录获取姓名和电子邮件。

我正在使用:compile 'com.facebook.android:facebook-android-sdk:4.+'

我可以进入onSuccess,但代码没有进入GraphRequest,我认为这就是为什么我无法获取姓名和电子邮件(我也喜欢获取个人资料照片) )

我从facebook developer Explorer Api Graph获得了自动生成的代码(GraphRequest)

public class LoginActivity
{

 LoginButton buttonLoginFacebook;

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.login);

        buttonLoginFacebook = (LoginButton) findViewById(R.id.connectWithFbButton);

        buttonLoginFacebook.setReadPermissions(Arrays.asList(
                "public_profile", "email"));

        FacebookSdk.setIsDebugEnabled(true);
        FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        FacebookSdk.addLoggingBehavior(LoggingBehavior.REQUESTS);


        buttonLoginFacebook.setOnClickListener(this);


        buttonLoginFacebook.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {


            @Override
            public void onSuccess(LoginResult loginResult) {


             //----->THE CODE JUMPS FROM HERE
             GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {

                                mensajeFACEBOOK="TRYING TO GET NAME";
                            }
                        });

                //----->TO HERE
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,first_name,last_name");
                request.setParameters(parameters);
                request.executeAsync();


                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);

            }

          @Override
            public void onCancel() {    
            }    
            @Override
            public void onError(FacebookException error) {    
            }
        });


    }


}

2 个答案:

答案 0 :(得分:0)

我就是这样做的。希望这会有所帮助。

  private void registerCallBackMethod(){

    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(final LoginResult loginResult) {

                    final String accessToken = loginResult.getAccessToken().getUserId();

                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject jsonObject,
                                                        GraphResponse response) {

                                    // Getting FB User Data and checking for null
                                    Bundle facebookData = getFacebookData(jsonObject);
                                    String email = "";
                                    String first_name = "";
                                    String last_name = "";
                                    String profile_pic = "";

                                    if (facebookData.getString("email") != null && !TextUtils.isEmpty(facebookData.getString("email")))
                                        email = facebookData.getString("email");
                                    else
                                        email = "";

                                    if (facebookData.getString("first_name") != null && !TextUtils.isEmpty(facebookData.getString("first_name")))
                                        first_name = facebookData.getString("first_name");
                                    else
                                        first_name = "";

                                    if (facebookData.getString("last_name") != null && !TextUtils.isEmpty(facebookData.getString("last_name")))
                                        last_name = facebookData.getString("last_name");
                                    else
                                        last_name = "";

                                    if (facebookData.getString("profile_pic") != null && !TextUtils.isEmpty(facebookData.getString("profile_pic")))
                                        profile_pic = facebookData.getString("profile_pic");
                                    else
                                        profile_pic = "";


                                    sendValues(first_name+" "+last_name,email, "", "", accessToken, "Facebook",profile_pic);

                                }
                            });

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


                @Override
                public void onCancel () {
                    Log.d("TAG", "Login attempt cancelled.");
                }

                @Override
                public void onError (FacebookException e){
                    e.printStackTrace();
                    Log.d("TAG", "Login attempt failed.");
                    deleteAccessToken();
                }
            }
    );

}


private Bundle getFacebookData(JSONObject object) {
    Bundle bundle = new Bundle();

    try {
        String id = object.getString("id");
        URL profile_pic;
        try {
            profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?type=large");
            Log.i("profile_pic", profile_pic + "");
            bundle.putString("profile_pic", profile_pic.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

        bundle.putString("idFacebook", id);
        if (object.has("first_name"))
            bundle.putString("first_name", object.getString("first_name"));
        if (object.has("last_name"))
            bundle.putString("last_name", object.getString("last_name"));
        if (object.has("email"))
            bundle.putString("email", object.getString("email"));
        if (object.has("gender"))
            bundle.putString("gender", object.getString("gender"));


    } catch (Exception e) {
        Log.d("TAG", "BUNDLE Exception : "+e.toString());
    }

    return bundle;
}

private void deleteAccessToken() {
    AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(
                AccessToken oldAccessToken,
                AccessToken currentAccessToken) {

            if (currentAccessToken == null){
                //User logged out

                LoginManager.getInstance().logOut();
            }
        }
    };
}

答案 1 :(得分:0)

实际上GraphRequest.executeAsync()是一个带回调onCompleted的异步方法,所以要在回调中读取你需要做的数据。

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

                                //Read the data you need from the GraphResponse here like this: 

                                try {
                                    String firstName = response.getJSONObject().getString("first_name");
                                    String lastName = response.getJSONObject().getString("last_name");
                                    String email = response.getJSONObject().getString("email");
                                    String id = response.getJSONObject().getString("id");
                                    String picture = response.getJSONObject().getJSONObject("picture").getJSONObject("data").getString("url");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                            }
                        });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,first_name,last_name,picture.width(150).height(150)");
                request.setParameters(parameters);
                request.executeAsync();

            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException error) {
            }
        });

还包括您提出的个人资料图片字段picture.width(150).height(150)