Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable loses value

Tags:

android

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?

like image 296
Iulia Barbu Avatar asked Dec 19 '11 15:12

Iulia Barbu


2 Answers

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

like image 157
Code Poet Avatar answered Oct 04 '22 16:10

Code Poet


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.

like image 21
Alexander Kulyakhtin Avatar answered Oct 04 '22 17:10

Alexander Kulyakhtin