I have an android java class with a static instance holding info on a user. However, in some rare cases with a user using my app, one of the variables within that static instance becomes null after a while. This java class is global (not attached to any activity). What could be causing this?
EDIT: The variable is never changed except during the startup of the app. I've already checked that the function calling it will never be called more than once (the adb logcat proves that when I added a log stating that it is being called).
The code is something like this:
class UserCore
{
class UserData
{
int ID;
string Name;
}
public UserData User;
public static UserCore Instance = new UserCore();
public void Login()
{
Log.d("User", "Logging in");
new Throwable().printStackTrace();
User = null;
//Fetch user data
User = new UserData();
User.ID = ...
User.Name = ...
}
....
}
解决方案
This generally would happen if the user lets the phone go to sleep and the system requires or clears memory. It's best to keep information that you would require over a longer duration into a disk cache rather than just keeping it in a static variable. As you would know that the Android system has the final say on when to clear an app, only keep data that you would need for a very short interaction in a static variable.