Static variable loses value

后端 未结 2 2079
难免孤独
难免孤独 2021-01-18 08:53

I\'m facing an issue regarding a static variable that i\'m am using all over my project(it contains some fields from a file). The variable loses her value in some cases, not

2条回答
  •  礼貌的吻别
    2021-01-18 09:34

    If you really must use static/globals put them into your custom class which extends Application. Like this:

    public class FooApplication extends Application {
        protected Bar myBar;
    
        public Bar getBar() { return myBar; }
        public void setBar(Bar bar) { myBar = bar; }
        ...
    }
    

    Declare that you'll be using a custom Application class using your manifest.

    
    

    Now you can access your application object from any activity using (FooApplication) getApplication(). Please note that this is not the recommended method. The recommended method is to use singleton pattern.

    If the parsing of the file is an expensive operation you might not want to parse it on every onResume. Instead you might want to consider using onRetainNonConfigurationInstance()

提交回复
热议问题