How to use static variables in activities

As previously described in Leaving an Android application, when you exit an app by pressing back button its resources are not completely destroyed immediately.

I would like to explain a concrete mistake I met multiple times, in connection with this behavior, which is easy to commit, if you forget this.

When you use static member variables in an activity you, should think about, how static variables are handled when instantiating, and how android instantiates activities.

If a static variable has an initial value it is only applied when creating the first instance. When the activity is started, when starting from app browser or by an Intent programmatically by you it becomes instantiated. When the app is first started, the first instance will be created, so obviously the static variables will get the initial values.

During the run the static variables may be killed if the activity they belong to are not visible, in this case they will have their default values when returning to the activity. If you want to restore their values in this case from some kind of stored source read this article: Maintaining global Application state

And the problem I recently met, that the opposite can also happen, the static variables may keep their values when you did not expect this. It is very easy to confirm this, just exit the application by pressing back and quickly restart it from the app browser. In such a sort time the android system will not kill the entire activity, and static variables will retain values.

So you should think over why the variable become static, to decide if it is the desired behavior for you or not. For example you can reinitialize the static variables in onCreate or onResume methods if that fits you.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s