我正在开发一个android应用程序,想要使用savedInstanceState保存一个rand2( double 类型)值,这样我就可以在应用程序重新打开时使用rand2值,但在检索rand2值时它总是为NULL,要么该值未保存,要么该值未检索。为什么会发生这种情况?我应该如何保存 rand2 值,以便在重新打开应用程序时可以重用它?
public class MainActivity extends AppCompatActivity {
double rand2;
private boolean started = false;
private Handler handler = new Handler();
public Runnable runnable = new Runnable() {
@Override
public void run() {
double rand1 = Math.random() * 5;
rand2 = rand2 + rand1 * 0.04;
DecimalFormat df = new DecimalFormat("0.00");
String message1 = "" + df.format(rand1);
DecimalFormat dff = new DecimalFormat("000000.00");
String message2 = "" + dff.format(rand2);
displayRate(message1);
displaySatoshi(message2);
if (started) {
start(started);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// recovering the instance state
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
if (savedInstanceState != null) {
rand2 = savedInstanceState.getDouble("abc");
} else {
rand2 = 0.00;
}
setContentView(R.layout.activity_main);
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(withdraw);
// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
@Override
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, Withdraw.class);
startActivity(numbersIntent);
}
});
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putDouble("abc", rand2);
// call superclass to save any view hierarchy
super.onSaveInstanceState(savedInstanceState);
}
public void Start(View v) {
ToggleButton starStopTogglrButton = (ToggleButton) findViewById(R.id.start_stop);
boolean hasStartStop = starStopTogglrButton.isChecked();
if (hasStartStop) {
start(hasStartStop);
} else {
stop(hasStartStop);
}
}
public void stop(Boolean hasStartStop) {
//Checking start or stop
started = hasStartStop;
handler.removeCallbacks(runnable);
}
public void start(Boolean hasStartStop) {
started = hasStartStop;
handler.postDelayed(runnable, 1000);
}
private void displayRate(String message1) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.rate);
orderSummaryTextView.setText(message1);
}
private void displaySatoshi(String message2) {
TextView orderSummaryView = (TextView) findViewById(R.id.satoshis);
orderSummaryView.setText(message2);
}
}
最佳答案
onSaveInstanceState
在应用程序关闭时调用,但 onCreate 仅在应用程序完成后启动时调用。记住 Activity 生命周期:
因此,由于 onSaveInstanceState
在关闭时调用,而 onCreate 仅在(重新)创建 Activity 时调用,因此它为 null,因为当时尚未添加它。
您正在寻找onRestoreInstanceState
。重写该方法并获取变量并从那里分配它。
请记住,如果 Activity 完全销毁,使用 savingInstanceState 不会保存数据。对于持久数据存储,请使用共享首选项、文件或 SQL
关于java - 在java代码中使用savedInstanceState来保存可重用的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840556/