How to get Facebook photo, full name, gender using Facebook SDK android

試著忘記壹切 提交于 2019-11-28 17:16:50
chrisbjr

In your StatusCallback function, you can get the details from the GraphUser object

private class SessionStatusCallback implements Session.StatusCallback {
    private String fbAccessToken;

    @Override
    public void call(Session session, SessionState state, Exception exception) {
        updateView();
        if (session.isOpened()) {
            fbAccessToken = session.getAccessToken();
            // make request to get facebook user info
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    Log.i("fb", "fb user: "+ user.toString());

                    String fbId = user.getId();
                    String fbAccessToken = fbAccessToken;
                    String fbName = user.getName();
                    String gender = user.asMap().get("gender").toString();
                    String email = user.asMap().get("email").toString();

                    Log.i("fb", userProfile.getEmail());
                }
            });
        }
    }
}

With new api and your custom button for facebook you can use below code:

put below gradle in your gradle file:

 compile 'com.facebook.android:facebook-android-sdk:4.20.0'

  Newer sdk does not need initializaion .

    private CallbackManager callbackManager;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(LoginActivity.this);//Is now depricated
    setContentView(R.layout.activity_login);
    callbackManager = CallbackManager.Factory.create();
    }

onActivityResult:

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

Button Click:

   @Override
    public void onClick(View v) {
    switch (v.getId())
    {
        case R.id.btn_f_sign_in_login:
            LoginManager.getInstance().logInWithReadPermissions(
                    this,
                    Arrays.asList("user_friends", "email", "public_profile"));

            LoginManager.getInstance().registerCallback(callbackManager,
                    new FacebookCallback<LoginResult>() {
                        @Override
                        public void onSuccess(LoginResult loginResult) {
                            setFacebookData(loginResult);
                        }

                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onError(FacebookException exception) {
                        }
                    });
            break;
    }
}

setFacebookData:

     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 gender = response.getJSONObject().getString("gender");



                        Profile profile = Profile.getCurrentProfile();
                        String id = profile.getId();
                        String link = profile.getLinkUri().toString();
                        Log.i("Link",link);
                        if (Profile.getCurrentProfile()!=null)
                        {
                            Log.i("Login", "ProfilePic" + Profile.getCurrentProfile().getProfilePictureUri(200, 200));
                        }

                       Log.i("Login" + "Email", email);
                        Log.i("Login"+ "FirstName", firstName);
                        Log.i("Login" + "LastName", lastName);
                        Log.i("Login" + "Gender", gender);


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

get Facebook Friends Who has downoaded your app:

replace parameters.putString("fields", "id,email,first_name,last_name");

with parameters.putString("fields", "id,email,first_name,last_name,friends");

Add below logic to get friends Data

                if (object.has("friends")) {
                  JSONObject friend = object.getJSONObject("friends");
                  JSONArray data = friend.getJSONArray("data");
                  for (int i=0;i<data.length();i++){
                 Log.i("idddd",data.getJSONObject(i).getString("id"));
                  }
             }

with new API

private void importFbProfilePhoto() {

    if (AccessToken.getCurrentAccessToken() != null) {

        GraphRequest request = GraphRequest.newMeRequest(
                AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject me, GraphResponse response) {

                        if (AccessToken.getCurrentAccessToken() != null) {

                            if (me != null) {

                                String profileImageUrl = ImageRequest.getProfilePictureUri(me.optString("id"), 500, 500).toString();
                                Log.i(LOG_TAG, profileImageUrl);

                            }
                        }
                    }
                });
        GraphRequest.executeBatchAsync(request);
    }
}
mbecker

See The following tutorials

You have to make a request to the get the GraphUser-Object. With this object you can get the informations you want: GraphUser user.getName(); ,user.getId(); etc.

With Sdk v4.28 and for logged in Users as on question, it is easy as calling Profile.getCurrentProfile() inside (or after) success callback of LoginManager:

facebookCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(facebookCallbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult{ 
                    //Profile.getCurrentProfile()
                }
                @Override
                public void onCancel() {
                }
                @Override
                public void onError(FacebookException exception) {
                }
            });

You could use Graph Api, but doc itself says use above for logged in user.

if you will get the null profile then use Profile Tracker if(Profile.getCurrentProfile() == null) {

            mProfileTracker = new ProfileTracker() {
                @Override
                protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                    // profile2 is the new profile
                    Log.d("facebook - profile", profile2.getFirstName());
                    profile_firstname=profile2.getFirstName();
                    profile_lastname=profile2.getLastName();
                   // Toast.makeText(LoginActivity.this, "User ID : "+ profile2.getFirstName(), Toast.LENGTH_LONG).show();
                    mProfileTracker.stopTracking();
                }
            };

        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!