savedInstanceState给了我一个错误的值

问题描述:

我有一个秒表应用程序,它只有一个活动。三个按钮启动,停止,重置和一个文本视图来显示计时器。这里是我的代码: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穆里根谢谢。它让我疯狂 。多么愚蠢的错误。谢谢你。它是深夜晚上,我想我的大脑不能正常工作:) –

您可以通过在认沽(使用标签避免这种情况在未来)和get()调用:

private static final String KEY_NUM_SECS = "NUM_SECS"; 

然后使用它是这样的:

mNumberOfSeconds = savedInstanceState.getInt(KEY_NUM_SECS); 

和:

outState.putInt(KEY_NUM_SECS, mNumberOfSeconds); 
+0

谢谢。伟大的建议。我将来肯定会这样做。 –

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

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

你把价值与键“NUMBER_OF_SECONDS”但关键的“number_of_second”得到int值,这是放错了地方。