1

My problem is similar to this question Can't make static reference to non-static method ( Android getApplicationContext() ) I need to get the context of the SherlockFragmentActivity in order to access the database class. I tried the solution in this link above, but it did not work.

Question 1: How do I get the context in the code below.

Question 2: I get an error that forces me to use 'static' instead of public for the application context variable. I know that static is for a variable that does not change. However, this variable will change each time a tab is clicked on. Also, 'static' variables are not required for the database class. I'm confused as to why I need a static variable here.

my SherlockFragmentActivity:

public class FragmentTabs extends SherlockFragmentActivity {
    TabHost mTabHost;
    TabManager mTabManager;
    static FragmentTabs appState;
 TabSwitchIdDatabase tsid = new TabSwitchIdDatabase(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(SampleList.THEME); // Used for theme switching in samples
        super.onCreate(savedInstanceState);

        appState = ((FragmentTabs)getApplicationContext());

        //.... more code
}
 public static class TabManager implements TabHost.OnTabChangeListener {..// see code snipit below....}

}

Where i need to put the context

    public static class TabManager implements TabHost.OnTabChangeListener {

//... more code

static class DummyTabFactory implements TabHost.TabContentFactory {

//... more code

@Override
        public void onTabChanged(String tabId) {
            TabInfo newTab = mTabs.get(tabId);
            System.out.println(tabId);

            tsid.open();// broken , scoping problem
            Boolean x =tsid.tabExists(0);
            String tabIDfromDatabase = tsid.getTab(0);// broken , scoping problem
            tsid.close();// broken , scoping problem
}
}
}
Community
  • 1
  • 1
Leoa
  • 1,167
  • 2
  • 14
  • 31

2 Answers2

1

Are you sure the problem is related to the SherlockFragmentActivity itself?

Have you checked (for example) that you have specified android:name=".MyApplication" in your AndroidManifest.xml file?

thelawnmowerman
  • 11,956
  • 2
  • 23
  • 36
1

Do you have a constructor for your DummyTabFactory?

  • Pass the context as an argument to it.
  • Assign the passed context to a local variable.

So your code should look like something like this:

public class FragmentTabs extends SherlockFragmentActivity {
    DummyTabFactory mDummyTabFactory = new DummyTabFactory(getApplicationContext());

    static class DummyTabFactory implements TabHost.TabContentFactory {
        private Context mContext;

        public DummyTabFactory(Context context) {
            super(fm);
            mContext = context;
        }
    }
}

Now you can use mContext to access your app's resources.

ozbek
  • 20,955
  • 5
  • 61
  • 84