【发布时间】: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