Search code examples
androidfacebookfacebook-graph-apifacebook-android-sdk

Accessing Facebook username using Facebook android SDK


I am using facebook 3.15 android SDK. I am using following code to get the username and other details of the logged in user:

private final String[] PERMISSIONS = new String[] { "public_profile", "email" };

//this function gets called when user clicks on facebook login button
public void onFbButtonClick(View v) {
        Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setPermissions(Arrays.asList(PERMISSIONS)).setCallback(callback));
        } else {
            Session.openActiveSession(this, true, callback);
        }
}

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (state.isOpened()) {
        Log.i("Logged in...");
        // make request to the /me API
        Request.newMeRequest(session, new Request.GraphUserCallback() {
            // callback after Graph API response with user object
            @Override
            public void onCompleted(GraphUser user, Response response) {
                if (user != null) {
                    Log.d("user.getName : " + user.getName());
                    Log.d("user.getUsername : " + user.getUsername());
                    Log.d("user.getId : " + user.getId());
                    String email = user.getProperty("email").toString();
                    Log.d("user.email : " + email);
                }
            }
        }).executeAsync();
    } else if (state.isClosed()) {
        Log.i("Logged out...");
    }
}

My code is working fine except the part that where i am printing the username. It is showing null in the logs. Any idea why this is happening? I have provided the necessary permissions.


Solution

  • The field username is no longer existing in the Graph API v2.0, so you can't use it.

    See

    /me/username is no longer available