mudit
mudit

Reputation: 25536

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.

Upvotes: 0

Views: 5882

Answers (2)

piyush
piyush

Reputation: 145

but there's a trick you can use. After receiving the id you can make a call like this https://graph.facebook.com/{user_id} you will get the metadata of the user containing username.

P.S. To test it pick some id and check it in the browser. Hope it helps.

Upvotes: -1

Tobi
Tobi

Reputation: 31479

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

Upvotes: 2

Related Questions