Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session.getActiveSession() returns null when starting the app, although I'm connected

I use com.facebook.widget.UserSettingsFragment to manage login/logout to Facebook in my app:

UserSettingsFragment userSettingsFragment = new UserSettingsFragment();
Session session = Session.getActiveSession();
if(session==null || session.isClosed()){
    userSettingsFragment.setPublishPermissions(Arrays.asList("publish_actions"));
}
fragmentTransaction.replace(R.id.content_container, userSettingsFragment, "userSettingsFragment");

In another Fragment (but same Activity), Before publishing on Facebook I'm checking whether I'm logged using

Session session = Session.getActiveSession();
if (session != null && session.isOpened()){
    publishOnFacebook(intent.getExtras());
}

When I start my app and try to publish, I always get a null Session although I logged in before. And when I start UserSettingsFragment, it shows me that I'm connected.

How can Session.getActiveSession(); be null if I'm actually connected?

Moreover, if I I start the Fragment where I do the publishing straight after UserSettingsFragment, I get the correct Session, i.e.:

1 start the app
2 call `Session.getActiveSession()` in another `Fragment` returns `null`
3 start `UserSettingsFragment` shows that I'm log

but

1 start the app
2 start `UserSettingsFragment` shows that I'm log
3 call `Session.getActiveSession()` in another `Fragment` returns a session

Anybody can help?

like image 858
jul Avatar asked Aug 18 '13 05:08

jul


1 Answers

Ok, I've just read about openActiveSessionFromCache (not from Facebook doc though):

Session session = Session.getActiveSession(); 

if(session==null){                      
    // try to restore from cache
    session = Session.openActiveSessionFromCache(getActivity());
}

if(session!=null && session.isOpened()){    
    publishOnFacebook(intent.getExtras());  
}
else{
    login();
}
like image 188
jul Avatar answered Oct 13 '22 20:10

jul