【发布时间】:2012-06-01 17:39:49
【问题描述】:
按照 Soonil 的解释(How to declare global variables in Android?),我一直在使用 android.app.Application 的子类在我的 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实际上是一个Fragment(准确的说是SherlockFragmentActivity)。
任何想法为什么我不能像以前一样访问 appState,有没有好的解决方法?
非常感谢。
编辑:很好,Matt B。事实证明,我实际调用 getApplicationContext() 的地方在另一个类中。这是调用点:
public class MyActivity extends SherlockFragmentActivity {
public static class AccountListFragment extends SherlockListFragment {
MyApp appState = ((MyApp)getApplicationContext());
...
}
...
}
另外,如下所述,当我将调用更改为时,错误消失了
MyApp appState = ((MyApp)getActivity().getApplicationContext());
【问题讨论】:
-
我们能否看到您的活动中扩展 SherlockFragmentActivity 的实际代码?编辑:我在
SherlockFragmentActivity中尝试了Application appState = ((Application)getApplicationContext());,它编译得很好。 -
我没有看到您在此代码示例中的哪个位置尝试对该方法进行静态引用。你确定你发布了正确的行吗?
-
您能否将答案标记为正确?
标签: java android android-fragments android-context static