简体   繁体   中英

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM