2014-01-18 13 views
0

我目前正在研究一個小型Android遊戲。在選項菜單中,您可以選擇您想要播放的時間,15,30或45秒。我有一個加載這些值的倒數計時器。現在在我的onPause上,我想保存當前時間,然後從當時開始繼續。保存並在首選項中打開TimerTime

protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); 
     int cTime = Integer.valueOf(sharedPrefs.getString("playTimePref", null)); 
     TimerTime = cTime; 
     timer = new CountDownTimer(TimerTime, 1000) { 
      public void onTick(long millisUntilFinished) { 

       mTextField.setText("Seconds Remaining: " + millisUntilFinished/ 1000); 
       TimerTime = (int) millisUntilFinished; 
      } 

protected void onPause() { 
     SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); 
     editor.putString("playTimePref", "TimerTime"); 
     timer.cancel(); 
    } 

我認爲這會奏效。如果我沒問題,我將當前的TimerTime保存在onPause的playTimePref字符串中,然後在onResume上打開。但每次我回想起這個應用程序,時間都會重置到原來的時間。希望有人能幫忙。

+0

你需要提交編輯器後的編輯器 –

+0

嗨莫罕默德。感謝您的評論。我在原來的項目中有這個,只是忘了在這裏複製它。我嘗試了.apply和.commit,但兩者似乎沒有任何區別。 –

+0

如果我錯了,請糾正我,但是'PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext())'與'getPreferences(MODE_PRIVATE)'相同?如何在兩種方法上只使用一個表達式? –

回答

0

這種方法

final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); 

將創建一個與你的包名(com.xxx.xxx)共享偏好,並可以訪問由你的所有活動。

但這種方法

getPreferences(MODE_PRIVATE) 

將創建共享偏好與您的活動名稱(MainActivity),這將是訪問只與你的活動,因爲你指定的私人模式,所以你可以看到你嘗試保存你的數據在sharedPref並嘗試從另外一個訪問值,這就是爲什麼它爲你

您的代碼另一條評論返回null,則可以使用保存鑄造字符串的時候使用強類型爲int mehod

Editor.putInt("Key" , timenumber); 

希望它可以幫到你