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

跟風遠走 提交于 2019-12-08 18:03:05

问题


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());

回答1:


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



来源:https://stackoverflow.com/questions/10854930/cant-make-static-reference-to-non-static-method-android-getapplicationcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!