java 不能静态引用非静态方法(Android getApplicationContext())

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10854930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:51:59  来源:igfitidea点击:

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

javaandroidandroid-fragmentsandroid-contextstatic

提问by gcl1

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?).

我一直在使用 android.app.Application 的子类在我的 Android 应用程序中存储跨活动所需的全局变量,如 Soonil(在如何在 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).

与之前的关键区别在于新的Activity实际上是一个Fragment(准确地说是SherlockFragmentActivity)。

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

任何想法为什么我不能像以前那样访问 appState,有没有好的解决方法?

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:

编辑:很好,马特 B。事实证明,我实际调用 getApplicationContext() 的地方在另一个类中。这是调用点:

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

采纳答案by vanleeuwenbram

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

不同之处在于您现在是从 Fragment 调用此函数(即使您将其命名为“Activity”)而不是 Activity