问题描述
是一个错误的想法,创建一个单独的类,并将其用作仅包含静态数据变量的存储?
我目前正在为Android开发一个应用程序,但问题是Java将军.
如果是Android,我正在跨越活动,我想在那个单独的类中存储一些全局/静态标志/变量,并能够从我想要的任何活动访问它们.
ps.数据仅在会话时间中需要.
推荐答案
嗯,这不是一个坏主意.您可以在Android中使用此类类类型.但这里的小纠正.您可以使该类扩展应用程序,而不是维护包含静态数据的类,而不是维护静态数据,而是将该类扩展并使用它存储数据.
这是一个例子,
public class HelloApplication extends Application { private int globalVariable=1; public int getGlobalVariable() { return globalVariable; } public void setGlobalVariable(int globalVariable) { this.globalVariable = globalVariable; } @Override public void onCreate() { //reinitialize variable } }
在您的活动中,执行此操作,
(HelloApplication)getApplication()).setGlobalVariable(10); int valiable=((HelloApplication)getApplication()).getGlobalVariable();
并谈谈SharedPreference,只有在长时间存储值时才考虑使用它们.如果没有,您应该利用应用程序类并使用Setter和Getter,这是合法的方式.
其他推荐答案
您可以使用SharedPreference来存储标志和变量.
看这个 preference demo
其他推荐答案
而不是创建静态类以保存全局变量,我建议您使用应用程序类.
参见链接:
问题描述
Is it a bad idea creating a separate class and use it as a storage which consists only of static data variables?
I am currently developing an app for android, but the question is general for Java.
In case of android, I am moving across activities and I would like to store some global/static flags/varibles in that separate class and being able to access them from any activity I want.
PS. The data is required only for the session time.
推荐答案
Well, that's not a bad idea. You can use such type of a class in Android. But a small correction here. Instead of maintaining a class that holds static Data, you can make that class to extend Application class and use it store the data.
Here is a example,
public class HelloApplication extends Application { private int globalVariable=1; public int getGlobalVariable() { return globalVariable; } public void setGlobalVariable(int globalVariable) { this.globalVariable = globalVariable; } @Override public void onCreate() { //reinitialize variable } }
And in your Activity, do this,
(HelloApplication)getApplication()).setGlobalVariable(10); int valiable=((HelloApplication)getApplication()).getGlobalVariable();
And speak about SharedPreference, you should consider using them only when the value has to be stored for a long time. if not, you should make use of the Application class and use setters and getters which is the legitimate way to do this.
其他推荐答案
You can use SharedPreference to store flags and variables .
Look at this Preference Demo .
其他推荐答案
Instead of Creating a Static class to save Global Variables, I would suggest you to use Application class.
see Link: