Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on an Android application in which any Android user who is logging to Facebook using our Application, I need to extract his photo, his gender, his full name from the Facebook. I am using Facebook SDK for this.

With the help of Facebook SDK, I am able to login into Facebook but I am not sure how to extract his photo,gender and full name from the facebook?

Below is the code I am using to login into Facebook. I followed this tutorial

public class SessionLoginFragment extends Fragment {

    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";

    private TextView textInstructionsOrLink;
    private Button buttonLoginLogout;
    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment, container, false);

    buttonLoginLogout = (Button) view.findViewById(R.id.buttonLoginLogout);
    textInstructionsOrLink = (TextView) view.findViewById(R.id.instructionsOrLink);

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
        session = Session.restoreSession(getActivity(), null, statusCallback,
            savedInstanceState);
        }
        if (session == null) {
        session = new Session(getActivity());
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        }
    }

    updateView();

    return view;
    }

    @Override
    public void onStart() {
    super.onStart();
    Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
    super.onStop();
    Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Session session = Session.getActiveSession();
    Session.saveSession(session, outState);
    }

    private void updateView() {
    Session session = Session.getActiveSession();
    if (session.isOpened()) {
        Log.d("Hello", URL_PREFIX_FRIENDS + session.getAccessToken());
        Intent i = new Intent(getActivity(), ThesisProjectAndroid.class);
        startActivity(i);

    } else {
        Log.d("Hello", "Login Failed");
        textInstructionsOrLink.setText(R.string.instructions);
        buttonLoginLogout.setText(R.string.login);
        buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickLogin();
        }
        });
    }
    }

    private void onClickLogin() {
    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
    } else {
        Session.openActiveSession(getActivity(), this, true, statusCallback);
    }
    }

    private void onClickLogout() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
    }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        updateView();
    }
    }
}

Can anyone tell me where I need to make changes in the above class to get all the three information I needed. As far as I know If I am able to get facebook unique id for that person, I can get all the information I guess. Any thoughts?

like image 525
arsenal Avatar asked Jan 26 '13 22:01

arsenal


2 Answers

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"));
                  }
             }
like image 136
Rajat Avatar answered Oct 23 '22 19:10

Rajat


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());
                }
            });
        }
    }
}
like image 23
chrisbjr Avatar answered Oct 23 '22 19:10

chrisbjr