我一直在存储多数民众赞成需要整个活动在我的Android应用程序使用android.app.Application的子类,由Soonil的解释(中的 Android的:?如何声明全局变量)
该方法是这样的:
类MyApp的扩展应用{
私人字符串myState;
公共字符串的getState(){
返回myState;
}
公共无效的setState(String s)将{
myState =秒;
}
}
类胡说延伸活动{
@覆盖
公共无效的onCreate(包B){
...
的MyApp appState =((MyApp的)getApplicationContext());
字符串状态= appState.getState();
...
}
}
到现在为止,这种方法已经从我的任何活动访问全局变量工作的罚款。但是用同样的方法在今天,我得到了以下错误:
无法使静态引用非静态方法getApplicationContext()
从类型ContextWrapper
从之前的主要区别是,新的活动实际上是一个片段(SherlockFragmentActivity,为precise)。
任何想法,为什么我不能访问appState,因为我有过,而且是有没有好的解决办法?
非常感谢。
编辑:好抓,马特B.它原来的地方,我实际调用getApplicationContext()是另外一个类的内部。这里的调用点:
公共类MyActivity扩展SherlockFragmentActivity {
公共静态类AccountListFragment扩展SherlockListFragment {
的MyApp appState =((MyApp的)getApplicationContext());
...
}
...
}
另外,如下所述,错误走了,当我改变调用
MyApp的appState =((MyApp的)getActivity()getApplicationContext());
解决方案
getActivity()。getApplication()
应该只是罚款。
您首先需要提及的活动,再到应用程序
不同的是,你现在从一个片段调用这个函数(即使你把它命名为活动),而不是一个活动
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 Android: How to declare global variables?).
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());
解决方案
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