Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make static reference to non-static method ( Android getApplicationContext() )

I have been storing a global variable that's needed across Activities in my Android app by using a subclass of android.app.Application as explained by Soonil (in How to declare global variables in Android?).

The approach looks like this:

class MyApp extends Application {

    private String myState;

    public String getState(){
    return myState;
    }
        public void setState(String s){
        myState = s;
    }
}

class Blah extends Activity {

    @Override
    public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
    }
}

Up to this point, this approach has worked fine for accessing the global variable from any of my Activities. But today using the same approach, I got the following error:

Cannot make a static reference to the non-static method getApplicationContext()
from the type ContextWrapper

The key difference from before is that the new Activity is actually a Fragment (SherlockFragmentActivity, to be precise).

Any ideas why can't I access appState as I have before, and is there a good workaround?

Many thanks.


EDIT: Good catch, Matt B. It turns out the place I'm actually calling getApplicationContext() is inside another class. Here's the calling point:

public class MyActivity extends SherlockFragmentActivity {
    public static class AccountListFragment extends SherlockListFragment {
        MyApp appState = ((MyApp)getApplicationContext());
        ...
    }
    ...
}

Also, as noted below, the error went away when I changed the call to

MyApp appState = ((MyApp)getActivity().getApplicationContext());
like image 287
gcl1 Avatar asked Jun 01 '12 17:06

gcl1


1 Answers

getActivity().getApplication() 

should work just fine.

You first need a reference to activity, then to application

The difference is that you are now calling this function from a Fragment (even though you named it "Activity") instead of an Activity

like image 111
vanleeuwenbram Avatar answered Oct 18 '22 21:10

vanleeuwenbram