【问题标题】:Why wont my app save 2 values and then display them the next time the app is open?为什么我的应用程序不保存 2 个值,然后在下次打开应用程序时显示它们?
【发布时间】:2014-12-03 12:58:11
【问题描述】:

我最近了解了 SharedPreferences,现在我尝试将它放入我的代码中。我有 2 个整数值,称为 counter 和 counterPS。我想要发生的是应用程序将每 5 秒保存一次值,然后当应用程序完全关闭并完全重新打开时(例如手机关闭并再次打开)我希望应用程序查看是否保存的值(如果它们甚至是)大于 0,如果是,则将当前值设置为旧保存的值。但是,我为应用程序内的值设置了一个数字并等待五秒钟以保存它,当我完全重新启动应用程序时,值刚刚出现为 0。为什么会这样,有人可以告诉我如何解决这个问题吗?

  protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    SharedPreferences saving = getSharedPreferences("ShipData", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = saving.edit();

    int counter = saving.getInt("shipCounter", 0);
    int counterPS = saving.getInt("shipCounterPS", 0);

    if(mShip.getCounter() == 0) {
        if (counter > 0) {
            mShip.setCounter(counter);
            mShip.setCounterPerSec(counterPS);
        }
    }


    //Save values every 5 seconds Below
    new TimerClass(5000, 1000)
    {
        public void OnFinish()
        {
            editor.putInt("ShipCounter", mShip.getCounter());
            editor.putInt("ShipCounterPS", mShip.getCounterPerSec());
            editor.commit();
            this.start();
        }
    }.start();
}

【问题讨论】:

  • 我想问一下你的 TimerClass 类是否经过测试。另外,请记住,editor.commit(); 如果保存成功则返回 true,否则返回 false,您可能需要检查一下。

标签: java android sharedpreferences


【解决方案1】:

如何使用处理程序(android 方式)而不是计时器类?它适合你的情况吗?

更多信息:

http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/

我知道这个问题是不久前发布的。只是回复它以解决类似的未来问题......谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2021-11-07
    • 2021-05-06
    • 1970-01-01
    相关资源
    最近更新 更多