2014-10-08 44 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

回答

相關問題