java – 无法对非静态方法进行静态引用(Android getApplicationContext())

我已经在我的 Android应用程序中的活动中存储了一个全局变量,使用了一个android.app.Application的子类,如Soonil( How to declare global variables in Android?)所述.

方法如下:

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

到目前为止,这种方法适用于从我的任何活动中访问全局变量.但是今天使用相同的方法,我得到以下错误

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

与之前的关键区别在于新的Activity实际上是一个片段(SherlockFragmentActivity,确切地说).

任何想法为什么我不能像以前那样访问appState,并且有一个很好的解决方法吗?

非常感谢.

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

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

此外,如下所述,当我将呼叫更改为时,错误消失了

MyApp appState = ((MyApp)getActivity().getApplicationContext());

解决方法

getActivity().getApplication()

应该工作得很好.

首先需要引用活动,然后引用应用程序

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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...