Java静态变量变成空量变、静态、成空、Java

由网友(半根烟闯江湖)分享简介:我有一个Android的Java类与用户的静态实例持有信息。然而,在某些罕见的情况下,与用户使用我的应用程序,静态实例中的变量之一了一段时间后变为零。该Java类是全球性的(未连接到任何活动)。这可能是造成这?编辑:变量是永远不会改变,除非应用程序的启动过程中。我已经检查了函数调用它永远不会被调用一次以上(在亚行log...

我有一个Android的Java类与用户的静态实例持有信息。然而,在某些罕见的情况下,与用户使用我的应用程序,静态实例中的变量之一了一段时间后变为零。该Java类是全球性的(未连接到任何活动)。这可能是造成这?

编辑:变量是永远不会改变,除非应用程序的启动过程中。我已经检查了函数调用它永远不会被调用一次以上(在亚行logcat证明,当我添加了一个日志,说明它被调用)。

在code是这样的:

 类UserCore
{
    一流的UserData
    {
        INT ID;
        字符串名称;
    }

    公众的UserData用户;
    公共静态UserCore实例=新UserCore();

    公共无效登录()
    {
        Log.d(用户,登录);
        新的Throwable()的printStackTrace()。

        用户=无效;
        //获取用户数据
        用户=新的UserData();
        User.ID = ...
        User.Name = ...
    }
    ....
}
 

解决方案

这如果用户让手机进入睡眠状态,并在系统需要或清除内存通常会发生。这是最好把你需要在一个较长的持续时间为一个磁盘缓存,而不是仅仅保存在一个静态变量的信息。正如你所知道,Android系统对时清除应用说了算,只保留数据,你需要在一个静态变量在很短的互动。

一个Java类在运行时候,变量是怎么在JVM中分布的呢

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.

阅读全文

相关推荐

最新文章