2017-08-10 109 views
1

我有一個秒錶應用程序,它只有一個活動。三個按鈕啓動,停止,重置和一個文本視圖來顯示計時器。這裏是我的代碼:savedInstanceState給了我一個錯誤的值

public class StopwatchActivity extends AppCompatActivity { 

private int mNumberOfSeconds = 0; 
private boolean mRunning = false; 
private Handler handler = new Handler(); 
private Runnable runnable; 
private TextView timeview; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_stopwatch); 

    if (savedInstanceState != null){ 
     mNumberOfSeconds = savedInstanceState.getInt("number_of_second"); 
     mRunning = savedInstanceState.getBoolean("is_running"); 
     Log.e("after orient mSecond :" , String.valueOf(mNumberOfSeconds)); 
     Log.e("after orient mRunning :" , String.valueOf(mRunning)); 
     runner(); 
    } 

} 

public void onClickStart(View view){ 
    handler.removeCallbacks(runnable); 
    mRunning = true; 
    runner(); 
} 

public void onClickStop(View view){ 
    mRunning = false; 
    handler.removeCallbacks(runnable); 
} 

public void onClickReset(View view){ 
    mRunning = false; 
    //mNumberOfSeconds = 0; 
    //timeview.setText("0:00:00"); 


} 

public void runner(){ 
    timeview = (TextView) findViewById(R.id.time_view); 
    runnable = new Runnable() { 
     @Override 
     public void run() { 
      int hours = mNumberOfSeconds/3600; 
      int minutes = (mNumberOfSeconds%3600)/60; 
      int second = mNumberOfSeconds%60; 
      String time = String.format("%d:%02d:%02d" , hours , minutes , second); 
      timeview.setText(time); 
      if (mRunning){ 
       mNumberOfSeconds++; 
      } 
      handler.postDelayed(this , 1000); 
     } 
    }; 
    handler.post(runnable); 

} 

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    outState.putInt("number_of_seconds" , mNumberOfSeconds); 
    outState.putBoolean("is_running" , mRunning); 
    Log.e("befor rotation second:" , String.valueOf(mNumberOfSeconds)); 
    Log.e("befor rotaion mrunning" , String.valueOf(mRunning)); 

} 

我要救我的一些的onSaveInstanceState中的變量來改變方向後再次獲得它們的使用。正如你可以在代碼中看到的日誌消息之前和方位的變化後顯示mNumberOfSeconds和mRunning的價值。並且在方向改變之後,mNumberOfSeconds會給我0而不是我保存的值。但mRunning給了我正確的價值。誰能給我任何解決方案?

+2

當把秒數爲您使用「NUMBER_OF_SECONDS」爲重點的包,但閱讀您使用「number_of_second」的值時。讀取該值時缺少「s」。 –

+0

@George穆里根謝謝。它讓我瘋狂 。多麼愚蠢的錯誤。謝謝你。它是深夜晚上,我想我的大腦不能正常工作:) –

回答

1

您可以通過在認沽(使用標籤避免這種情況在未來)和get()調用:

private static final String KEY_NUM_SECS = "NUM_SECS"; 

然後使用它是這樣的:

mNumberOfSeconds = savedInstanceState.getInt(KEY_NUM_SECS); 

和:

outState.putInt(KEY_NUM_SECS, mNumberOfSeconds); 
+0

謝謝。偉大的建議。我將來肯定會這樣做。 –

1

如果我比較你的代碼,你可以清楚地看到它:

outState.putInt("number_of_seconds" , mNumberOfSeconds); 
mNumberOfSeconds = savedInstanceState.getInt("number_of_second"); 

你把價值與鍵「NUMBER_OF_SECONDS」但關鍵的「number_of_second」得到int值,這是放錯了地方。