Java静态变量变成空

Java静态变量变成空

本文介绍了Java静态变量变成空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在code是这样的:

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

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

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

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

解决方案

这如果用户让手机进入睡眠状态,并在系统需要或清除内存通常会发生。这是最好把你需要在一个较长的持续时间为一个磁盘缓存,而不是仅仅保存在一个静态变量的信息。正如你所知道,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 = ...
    }
    ....
}
解决方案

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.

这篇关于Java静态变量变成空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:40