2014-10-08 41 views
0

我最近了解到SharedPreferences,现在我试着把它放在我的代码中。我有2个整数值称为计数器和计数器。我想要发生的事情是,应用程序会每隔5秒保存一次值,然后当应用程序完全关闭并完全重新打开时(例如关闭手机并再次打开),我希望应用程序查看是否保存了值(如果它们甚至是)大于0,如果是,则将当前值设置为旧保存的值。然而,我为应用程序内的值设置了一个数字,并等待了五秒钟以保存,当我重新启动应用程序时,值完全变为0.为什么是这样的,并且有人能告诉我如何解决这个问题?为什么我的应用程序不保存2个值,然后在应用程序下次打开时显示它们?

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(); 
} 
+0

我会问你的类TimerClass是否经过测试。另外,请记住,'editor.commit();'如果成功保存则返回true,否则返回false,您可能需要检查它。 – Logain 2014-10-08 19:56:19

回答

相关问题