Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Static Variable becomes null [duplicate]

Tags:

java

android

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 = ...
    }
    ....
}
like image 254
Little Coding Fox Avatar asked May 24 '13 13:05

Little Coding Fox


People also ask

Can static variables be null?

Static variable can only be null if it's on it's class. If you call the static variable from different class the result is NOT null.

Can we assign null to static variable in Java?

We cannot assign null to primitive variables e.g int, double, float, or boolean. If we try to do so, then the compiler will complain. The java instanceof operator which is also known as type comparison operator, tests whether the object is an instance of the specified type (class or subclass or interface).

Is static variable shared?

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.

Can static variables be declared twice?

Yes it is. Each of your b variables is private to the function in which they are declared. Show activity on this post. b in func and b in main are two different variables, they are not related, and their scope is inside each function that they are in.


1 Answers

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.

like image 194
Sam Avatar answered Oct 18 '22 04:10

Sam