Eugene Chumak
Eugene Chumak

Reputation: 3192

Can static variable value be nulled by system in android app?

I have noticed, that when android OS closes activities which are not in the top of activity stack, some of my static variables become null. I'm absolutely sure, the variables pointed to objects before and that I did not change their value by myself.

After activity recreation I get nullPointerException cause one of my static variable (which is initialized in Application's subclass onCreate and is supposed to be not null at any time of process lifecycle) is null.

Since its not me who nulls the variable, I suppose it is android OS which closes background activities and nulls static variables due to lack of memory. Is it possible?

Upvotes: 1

Views: 1358

Answers (2)

David Wasser
David Wasser

Reputation: 95578

Android does not close activities which are not on top of the activity stack. If your application goes to the background and Android decides that it wants to reclaim the memory it just kills the process that hosts your activities. When the user returns to the application, Android creates a new process and recreates the activity that was on the top of the activity stack.

In most probability, that's what you are seeing. Obviously if your process is killed and recreated, your static variables will be null.

Upvotes: 2

Kaediil
Kaediil

Reputation: 5535

They are only being nulled if the underlying VM/Thread that the activity was running in was killed. then it is like you are completely restarting the application. Don't rely on static variables, if you need to keep something around, store it in a DB or a Preference.

Upvotes: 1

Related Questions