Android: Passing a Facebook session across activities

android, facebook

Solution

Using SharedPreferences to pass data across activities is not good idea. SharedPreferences used to store some data into memory across application restart or device re-boot.

Instead you have two options:

Declare a static variable to hold facebook session, which is simplest method, but I wont recommend to use Static Fields as far there is no other way.

Make an class implementing parcelable, and set your facebook object there, see an parcelable implementation as follows:

// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
    private int mData;

    /* everything below here is for implementing Parcelable */

    // 99.9% of the time you can just ignore this
    public int describeContents() {
        return 0;
    }

    // write your object's data to the passed-in Parcel
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

Problem

I'm looking to pass a Facebook session across activities. I saw the example from Facebook's SDK and someone mentioned that the "Simple" example has a way to do this: `https://github.com/facebook/facebook-android-sdk/blob/master/examples/simple/src/com/facebook/android/SessionStore.java` But how does this work? In my `MainActivity`, I have this: ``` mPrefs = getPreferences(MODE_PRIVATE); String accessToken = mPrefs.getString("access_token", null); long expires = mPrefs.getLong("access_expires", 0); if (accessToken != null) { //We have a valid session! Yay! facebook.setAccessToken(accessToken); } if (expires != 0) { //Since we're not expired, we can set the expiration time. facebook.setAccessExpires(expires); } //Are we good to go? If not, call the authentication menu. if (!facebook.isSessionValid()) { facebook.authorize(this, new String[] { "email", "publish_stream" }, new DialogListener() { @Override public void onComplete(Bundle values) { } @Override public void onFacebookError(FacebookError error) { } @Override public void onError(DialogError e) { } @Override public void onCancel() { } }); } ``` But how do I pass this along to my `PhotoActivity` activity? Is there an example of this being implemented?

Original source