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 always. I have read about the life cycle of a static variable , that she loses the value in 3 cases :
1) Class is unloaded.
2) JVM shuts down.
3) The process dies.
So I have a question : Isn't enough to rewrite activities onResume and parse the file again and feed the static variable again if it is null?
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With