0

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.

mudit
  • 25,306
  • 32
  • 90
  • 132

2 Answers2

2

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

Tobi
  • 31,405
  • 8
  • 58
  • 90
-1

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.

piyush
  • 145
  • 3
  • 14
  • I got an OAuth error similar to the following after getting the token and the user ID: { "error": { "message": "An access token is required to request this resource.", "type": "OAuthException", "code": 104, "fbtrace_id": "A6jAr3L3eeh" } } – FractalBob Jun 18 '17 at 03:23