15

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 = ...
    }
    ....
}

1 Answers1

19

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.

Sam
  • 3,413
  • 1
  • 18
  • 20
  • 2
    So basically if I want to have data that will last the entire lifetime of the application I should save it in a file so I can fetch it whenever I need it rather than keep it globally. That's rather stupid if you ask me, but I guess I don't really have a choice... – Little Coding Fox May 24 '13 at 13:39
  • 2
    @LittleCodingFox See [this answer](http://stackoverflow.com/a/8023552/418609) for more info. Kind of subjective to say that this mechanism is stupid, don't forget you are running in a limited environment; and there are many [storage options](http://developer.android.com/guide/topics/data/data-storage.html) on Android. – adrianp May 24 '13 at 13:48
  • Android documentation for LRUCache `When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.` – Siddharth Jun 26 '15 at 05:30