7

I am trying to integrate facebook-connect to my android application. All the examples i am seeing over the internet are creating the connection from an Android activity. I am doing something a bit different, the user can configure its connection to facebook from a custom preference. I was successfull when doing it for twitter and foursquare. However, the method Facebook.authorize requires an Activity as parameter, and since i am inside a preference, i am not able to find any reference to an activity object.

So my question here is, how to get a reference for an activity inside a preference?

Thank you all T

Thiago
  • 5,152
  • 11
  • 35
  • 44
  • Could you post a small amount of code - just enough to illustrate what you have attempted so far? – Richard Ev Sep 16 '11 at 14:26
  • 2
    Richard... i manage to fix it. I just applied a cast to the context object (Activity) context and it worked fine. Not sure this is the correct way to achieve this, but as far it works, im fine! Thank you – Thiago Sep 16 '11 at 14:54

3 Answers3

9

I was able to get the Activity reference by casting the Context object to an Activity.

Activity activity = (Activity) context;

or with a custom activtity you can also do this

SettingsActivity activity = (SettingsActivity) context;
Camille Sévigny
  • 5,104
  • 4
  • 38
  • 61
  • Not always, e.g. see this [answer](http://stackoverflow.com/questions/7378644/how-to-call-getwindow-outside-an-activity-in-android/26871793#26871793) – Dimitar Jul 05 '16 at 17:21
4

It's an old question, though I use following function with the com.android.support:preference preferences fragment:

public static Activity getPrefActivity(Preference pref)
{
    Context c = pref.getContext();
    if (c instanceof ContextThemeWrapper)
    {
        if (((ContextThemeWrapper) c).getBaseContext() instanceof Activity)
            return (Activity) ((ContextThemeWrapper) c).getBaseContext();
    }
    else if (c instanceof Activity)
        return (Activity) c;
    return null;
}
prom85
  • 16,896
  • 17
  • 122
  • 242
0

Assuming you have an activity called MyActivity, can you just use MyActivity.class?

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
  • I tried this... and i am getting an error message like this one: "The method authorize(Activity, String[], int, Facebook.DialogListener) in the type Facebook is not applicable for the arguments (Class, String[], int, FacebookPreference.FbLoginDialogListener)"... and my call to that method is like this "mFacebook.authorize(CustomPreferencesActivity.class, ApplicationData.FACEBOOK_PERMISSIONS, -1, new FbLoginDialogListener());" – Thiago Sep 16 '11 at 14:11