In my application there is a class where I’ve declared some static variables. The problem is values for all the variables are not resetting when the application is destroyed.
Is there any way to reset the values of all the static variables when the application gets destroyed, except individually resetting them in onDestroy()?
In my application there is a class where I’ve declared some static variables. The
Share
You can reset static variables to
nullor any value you want but using static variables for other things then constants is usually a bad idea – it’s usually bad class design and can lead to unexpected behaviour like the one you observed.The value of static variables will persist as long as the class is loaded – it has almost nothing to do with Activity lifecycle (
onCreate, …,onDestroy)The first time you access a class from code it will get loaded and then it won’t go away until there is a reason to unload it. During that time anything from within your app (technically within the same Process – usually each .apk uses its own) will read the same value from those statics. And if you change it from different places you change it for other parts that don’t know of the change – that’s why it’s bad 🙂
The only reason (I know of) that Android will unload a class is that your app gets completely removed from memory – either via a task-killer or when your app is no longer active and memory gets low. That is completely out of your control and should not happen while your app is used. It could happen if e.g. a phone call comes in and your app resumes later.