我是新來的java。 我試圖在屏幕旋轉時將變量從OnSaveInstanceState
保存到OnCreate
。 我已將登錄的值保存到savedInstanceState
包中。 當屏幕旋轉時,在日誌中顯示的OnCreate(Bundle savedInstanceState)
中的Bundle值爲0,但在日誌中顯示爲OnSaveInstanceState
的正確值。捆綁丟失值
我的動態Java是
package com.hfad.stopwatch;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class StopwatchActivity extends Activity {
private static final String TAG = StopwatchActivity.class.getSimpleName();
private int seconds;
private boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
if(savedInstanceState != null){
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
seconds = savedInstanceState.getInt("seconds");
running = savedInstanceState.getBoolean("running");
String tmpStr = String.valueOf(seconds);
Log.d(TAG,tmpStr);
Log.d(TAG, "onCreate() ending");
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
runTimer();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG,"onSaveInstanceState() saving state");
savedInstanceState.putInt("Seconds", seconds);
savedInstanceState.putBoolean("running", running);
String tmpStr = String.valueOf(savedInstanceState.getInt("Seconds"));
Log.d(TAG,tmpStr);
Log.d(TAG,"onSaveInstanceState() ending");
}
//Start the stopwatch running when the start button is clicked
public void onClickStart(View view){
running = true;
}
//Stop the stopwatch running when the stop button is clicked
public void onClickStop(View view){
running = false;
}
//Start the stopwatch running when the start button is clicked
public void onClickReset(View view){
running = false;
seconds = 0;
}
private void runTimer(){
final TextView timeView = (TextView)findViewById(R.id.time_view);
final Handler handler = new Handler();
handler.post(new Runnable(){
@Override
public void run(){
int hours = seconds/3600;
int minutes = (seconds%3600)/60;
int secs = seconds%60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running){
seconds++;
}
handler.postDelayed(this, 1000);
}
});
}
}
這是日誌。
07-26 21:02:19.880 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onSaveInstanceState() saving state
07-26 21:02:19.880 6124-6124/com.hfad.stopwatch D/StopwatchActivity: 11
07-26 21:02:19.880 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onSaveInstanceState() ending
07-26 21:02:19.940 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onCreate() Restoring previous state
07-26 21:02:19.940 6124-6124/com.hfad.stopwatch D/StopwatchActivity: 0
07-26 21:02:19.940 6124-6124/com.hfad.stopwatch D/StopwatchActivity: onCreate() ending
我在一本書中學習下面的內容,但是這不起作用,並且我無法在線找到解決方案。
你應該標記爲接受,如果它幫助你的答案之一。請遵循SO的規則。 – Intern