Static variable loses value

后端 未结 2 2080
难免孤独
难免孤独 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:25

    You my want to make sure, first, that you don't inadvertently reset that variable yourself. For this you may want to create, say, getMyVariable() and setMyVariable() functions, put some logging into them and use them instead of accessing the variable directly.

    0 讨论(0)
  • 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.

    <application
        android:icon="@drawable/ic_launcher_noteit1"
        android:label="@string/app_name" 
        android:theme="@style/App_Theme"
        android:name="FooApplication" 
        android:debuggable="true">
    

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

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