How to get current access token in Facebook Android SDK V4?

Sujit Maharjan picture Sujit Maharjan · Apr 24, 2015 · Viewed 10.9k times · Source

I want to check whether the user is logged in or not within the main FragmentActivity but although the user is logged in

AccessToken.getCurrentAccessToken()

returns null. What am I doing wrong in the code below ?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;          
    FacebookSdk.sdkInitialize(context);
    callbackManager = CallbackManager.Factory.create();
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    if (accessToken != null) {
        if (!accessToken.isExpired()) {

        }
    }
}

Answer

Gokhan Caglar picture Gokhan Caglar · Apr 24, 2015

How is the user logging in, via the LoginButton? If so, it'll happen after they click the login button, so where you're checking is too early.

If they already logged in, then the access token is going to be deserialized from disk, however this is an async operation so that the UI thread is not blocked. You check it right after you initialize the Sdk, and the async operation is probably not completed yet. I suggest you use the AccessTokenTracker to respond when the AccessToken is loaded. Here's a sample that uses the AccessTokenTracker for your reference: https://github.com/facebook/facebook-android-sdk/blob/b384c0655fe96db71229bfdcb981a522f3f1e675/samples/Scrumptious/src/com/facebook/scrumptious/usersettings/UserSettingsFragment.java#L75