In my application I have Loginactivity. It has a static variable username and it will be assigned with the user enter values of username. Loginactivity launch activity A and A launch B. In A i use the variable Loginactivity.username.
Now due to some bug in B, application crashes. When I press force close, application is restarted and activity A is the current activity. In activity A I am using a static variable Loginactivity.username. I see that after crash this variable is getting its initial value which is empty string “”;
Why is it happening like this? Can you explain this behaviour? So when application crashes all the activities in the stack are restarted? I see that oncreate of Loginactivity is not getting called. Then how is the static variable value getting changed ?
Yes, when an application crashes, the jvm for this app is restarted, your classes are reloaded and you lose all static variables as well as instance variables.
The solution is to remove the crash cause. 🙂
When your Activity B crashes the Android Dalvik Virtual Machine that your application runs in (each app has its own DVM which are separate processes) is killed. When you are starting Activity A the username is “” because Java by defaults sets all instance variable (class variable or fields if you like) to null (references), 0 (primitives), and “” for strings. So your Activity A is working correctly. You just need to either store the username in the shared preferences, a database, or trigger the event for the user to login again… I would also fix Activity B… Haha
Use SharedPreferences instead, or store information in Application class
This is because you have a memory leak caused by this static member you keep in LoginActivity.
I would consider keeping this variable in Application scope (custom application class) or save it into DB.
Anyway, just remember to nullify this variable when your application is done.