Search code examples
androidfacebookglobal

Sharing a global facebook object across Android activities


I'm creating a global Facebook object (from android-facebook-sdk) to be able to share it across my activities:

public class GlobalVars extends Application {

    public static final String APP_ID = "123456789";    
    public Facebook facebook = new Facebook(APP_ID);

}

In one of the activities I add the LoginButton, as shown in the examples:

public class FacebookActivity extends Activity {

    private LoginButton mLoginButton;

    private Facebook mFacebook;    
    private AsyncFacebookRunner mAsyncRunner;    

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mFacebook = ((GlobalVars)getApplicationContext()).facebook;

        setContentView(R.layout.facebook);
        mLoginButton = (LoginButton) findViewById(R.id.login);
        mText = (TextView) FacebookActivity.this.findViewById(R.id.txt);

        mAsyncRunner = new AsyncFacebookRunner(mFacebook);

        SessionStore.restore(mFacebook, this);
        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        mLoginButton.init(this, mFacebook);

    }

    ...

}

Now, when I login and go to another activity using the same Facebook object:

public class MainActivity extends WhipemActivity {


    private Facebook mFacebook;    
    private AsyncFacebookRunner mAsyncRunner;   

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        mFacebook = ((GlobalVars)getApplicationContext()).facebook;

    }

    ....

}

and run a request such as:

mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mAsyncRunner.request("me/friends", new FriendRequestListener());

I get a

Facebook Error: Error validating access token.

What's wrong? Is it the correct way to have a global Facebook object?

Thanks.


Solution

  • jul, in your new activity, you need to restore the access token obtained during login.

    SessionStore.restore(mFacebook, this);
    

    SessionStore saves & restores the access token to/from SharedPreferences via a SharedPreferences object it creates.

    SessionStore.restore() gets the access token saved in SharedPreferences and sets it on the Facebook object.

    You can look in the "Facebook Example Simple" project and look at the SessionStore class to better see how SessionStore works.

    facebook-android-sdk/examples/simple