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()) {
}
}
}
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
Android Facebook sdk Initialization is take some time Initialize. so you need to wait just 100 milliseconds before calling AccessToken.getCurrentAccessToken()
once try this solution it is working for me
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
FacebookSdk.sdkInitialize(context);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
callbackManager = CallbackManager.Factory.create();
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
if (!accessToken.isExpired()) {
}
}
}
}, 100);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With