Using a class to store static data in Java?

前端 未结 7 643
醉梦人生
醉梦人生 2020-12-28 23:50

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 th

相关标签:
7条回答
  • 2020-12-29 00:25

    Instead of Creating a Static class to save Global Variables, I would suggest you to use Application class.

    see Link:

    Android global variable

    0 讨论(0)
  • 2020-12-29 00:25

    Well ! As far as I know It might depend on the size of your project ! If its relatively large its good to use separate class to store static data (not only one class , you might come in need of keeping them two or more classes depending on the type of the static data used)

    0 讨论(0)
  • 2020-12-29 00:29

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

    Taken from here..

    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.

    0 讨论(0)
  • 2020-12-29 00:29

    I would suggest that you should encapsulate your global class with a Singleton class. See more at Singleton Design Pattern

    0 讨论(0)
  • 2020-12-29 00:32

    i suggest that "never" use a global variables ....

    when you are accessing to another activity you can throw some values using Intent.putExtras(Name_parameter, "value_parameter")

    and to recive the value : Bundle b = getIntent().getExtras(); where b has all parameters

    cheers,

    0 讨论(0)
  • 2020-12-29 00:37

    use SharedPreference to store flags and variables

    http://developer.android.com/reference/android/content/SharedPreferences.html

    For Global variable:

    it would be better to use the Android Application class. It's meant to store global application state

    0 讨论(0)
提交回复
热议问题