Static variable traps
We all know that static variables are easy to use, but if you are not careful, say goodbye. Let's talk about the situation I encountered in the project. I tested it many times and finally found the cause. Moved!
Private static String UserRootPath = "/sdcard/User/" + UserManager. username;
Private static String UserCache = UserRootPath + "/path ";
Purpose:
In a class, the preceding two static variables are defined. To create different folders for logon by different users, UserManager. username is the user name.
Then it fell into the trap.
The situation is as follows:
When I log on to account A, the corresponding folder A is indeed created, but the login is logged out. When I log on again with another account B, the folder B is no longer created. Why: It has been A long time. During the test, we found that after logging on to B, UserManager is indeed changed to B, but UserRootPath is still the original "/sdcard/User/" +.
I have heard about the trap of static variables, so the static variables encountered a problem immediately.
The memory occupied by the UserRootPath after the activity or application is disabled is still in use. Therefore, the UserRootPath remains the original value when you log on again, and will not change, even if UserManager is used at this time. the username has changed. (when creating a folder, check whether the folder exists in the Code. Because the path is not changed, the result is that the folder already exists, so it won't be created again ). It turns out that if you disable the application and force kill the process of the application, this will not happen if you log on again.
So I assigned a value to UserRootPath again after login..
I thought it was done, but I found that the sub-directory of B was not created (+ _ + ).
The UserCache sub-directory references the UserRootPath, which is similar to the above situation. Because UserCache is also a static variable, although the UserRootPath is changed after login again, the UserCache is still the previous one (because there is no re-assignment, so the UserRootPath in it remains unchanged)
So I assigned a new value to UserCache after logging on..
Finally, I want to say that when I use a static variable, I will remember to update the value of the variable. Especially when the static variable references another variable, it is impossible to change the referenced variable only, the static variable value is also updated. (Because there is uncertainty about when static variables are recycled ).