Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Facebook user ID with android SDK 4.0

How can I get the Facebook User ID with the Facebook Android SDK 4.0?

Here is my code that doesn't work:

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_firstlogin);

    CallbackManager cm;
    LoginButton     lb;

    cm = CallbackManager.Factory.create();
    lb = (LoginButton) findViewById(R.id.facebook_button);
    Log.d(TAG, "Salut les zouzous");
    LoginManager.getInstance().registerCallback(cm,
            new FacebookCallback<LoginResult>()
            {
                @Override
                public void onSuccess(LoginResult loginResult)
                {
                   Log.d(TAG, "Success !");
                    AccessToken tok;
                    tok = AccessToken.getCurrentAccessToken();
                    Log.d(TAG, tok.getUserId());
                }

                @Override
                public void onCancel()
                {
                    Log.d(TAG, "On Cancel");
                }

                @Override
                public void onError(FacebookException exception)
                {
                    Log.e(TAG, exception.getMessage());
                }
            });

I precise that the

 Log.d(TAG, " Success"); 

doesn't print.

There is only the first log who print something, outside the callback.

Sorry for the bad English.

like image 455
Jidey Avatar asked Apr 22 '15 08:04

Jidey


Video Answer


3 Answers

As simple as

Profile.getCurrentProfile().getId()

This assumes the user is already logged in.

like image 71
Markymark Avatar answered Sep 25 '22 18:09

Markymark


You will need to do the following

 @Override
        public void onSuccess(LoginResult loginResult) {
            final AccessToken accessToken = loginResult.getAccessToken();

            GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject user, GraphResponse graphResponse) {
                    Log.d(TAG, user.optString("email"));
                    Log.d(TAG, user.optString("name"));
                    Log.d(TAG, user.optString("id"));
                }
            }).executeAsync();
        }
like image 22
Murtaza Khursheed Hussain Avatar answered Sep 22 '22 18:09

Murtaza Khursheed Hussain


just use loginResult.getAccessToken().getUserId() in onSuccess() as

@Override
public void onSuccess(LoginResult loginResult) {

    Toast.makeText(Login.this, "User ID : "+loginResult.getAccessToken().getUserId(), Toast.LENGTH_LONG).show();

}
like image 36
Hafiz Muneeb Avatar answered Sep 24 '22 18:09

Hafiz Muneeb