Not able to call facebook feature on other activitys
I am working with Facebook API using Android SDk. Here am facing one problem :
If I reside in same Activity (Single Activity) I am able to use the features like "Wall Post", "App Request" etc. But If I want those features on some other activity say third/fourth activity (upon navigation) I am not able to get access to the pages for "Wall Post" , "App request" etc. Can anyone help me out of this ? Please tell me if I am missing something. In every activity's oncreate() method, i m using setconnection() and getID(). Than I am calling facebook features from my facebook activity by using Menus.
Below is my code :
public void setConnection() {
mContext = this;
mFacebook = new Facebook(getResources().getString(R.string.FACEBOOK_ID_TEST));
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
public boolean isSession() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String access_token = sharedPrefs.getString("access_token", "x");
Long expires = sharedPrefs.getLong("access_expires", -1);
Log.d(TAG, access_token);
if (access_token != null && expires != -1) {
mFacebook.setAccessToken(access_token);
mFacebook.setAccessExpires(expires);
}
return mFacebook.isSessionValid();
}
public void getID()
{
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
if (isSession()) {
Log.d(TAG, "sessionValid");
try {
mFacebook.request("me/friends", bundle);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
开发者_C百科 // TODO Auto-generated catch block
Log.e("Error in FaceBook Friends List","Exception = "+e.getMessage());
e.printStackTrace();
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
}
You should not create new Facebook object for each activity. I recommend have a Utility class with static Facebook object which you initialize in your main activity and use this object though other activities.
E.g.
Class Utiltiy {
public static Facebook mFacebook;
public static void initialize() {
mFacebook = new Facebook(app_id);
}
}
You call Utility.initialize() in your main activity's onCreate()
and wherever you need to make Facebook API call, you can use:
Utility.mFacebook.request(....).
Hope this is helpful.
精彩评论