问题
I have some static variables in a class which extending the Application class .Now, somewhere in app ,if crash takes place then these are becoming null why it is so.
can i say clearly like, I am declaring those two variables in Application sub class and initializing in other java class when crash occurs these becoming null.my app requirement is after login only those two should be initialized.
For any answer/advice Thanks in advance
回答1:
Static variables are associated with a class and they will live as long as the class is in the memory(which ceases to exist once your application terminates or once the class gets unloaded, read this for further information). Hence, your static variables cease to exist when your application crashes, and again take up their values as null
.
For persistent value storage of these variables, opt for SharedPreferences
.
Read more about SharedPreferences here. And an example to work with.
回答2:
This behavior is normal. After your application crashes everything is "re-initialized" and your static
variables come to their initial values, which I suppose is null
.
If you want to keep your variables across application stop/restart (this will also happen when Android decides to stop your application) you should use a different storage, and I would suggest to look at SharedPreferences.
来源:https://stackoverflow.com/questions/11136693/static-variables-in-application-scope-are-null-when-app-crashes