我已经阅读了关于该主题的文档,在前景活动被销毁之前保存状态......
现在一切都很好(在设备旋转之后),但是当我在旋转后再次旋转设备时,我将再次丢失数据:(
这是我的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MainActivity activity = this;
activity.setTitle("Cow Counter");
TextView QntyResultField = findViewById(R.id.textView);
QntyResultField.setText(Integer.toString(cowQnty));
}
// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("qnty", cowQnty);
}
// How we retrieve the data after app crash...
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//cowQnty = savedInstanceState.getInt("qnty");
TextView QntyResultField = findViewById(R.id.textView);
QntyResultField.setText("Cows: "+Integer.toString(savedInstanceState.getInt("qnty")));
}
我认为解决方案可能是实现检查实例状态是否已经恢复...
我在这里尝试了这个:
if(savedInstanceState.getInt("qnty") != 0){
TextView QntyResultField = findViewById(R.id.textView);
QntyResultField.setText("Cows: "+Integer.toString(savedInstanceState.getInt("qnty")));
}
然后我的onCreate()方法中的初始部分将在我的结果字段中写入零
TextView QntyResultField = findViewById(R.id.textView);
QntyResultField.setText(Integer.toString(cowQnty));
有人能告诉我,我是否接近解决方案?
答案 0 :(得分:1)
您使用名为cowQnty
的变量将值保存在onSaveInstanceState
outState.putInt("qnty", cowQnty);
的捆绑包中,然后在onRestoreInstanceState
中恢复时仅将TextView
的值设置为检索到的值,并且不更新cowQnty
的值。
您如何期望再次保存空白字段?有两种解决方案;
首先,如果cowQnty
不是一个相当大的数量且您不介意使用大量的RAM,请将cowQnty
设为static
字段,它将保留数据而无需保存它完全在Bundle
。
其次,只需在恢复状态时再次设置cowQnty
的值(为什么要将其注释掉?),如下所示:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cowQnty = savedInstanceState.getInt("qnty");
TextView QntyResultField = findViewById(R.id.textView);
QntyResultField.setText("Cows: "+Integer.toString(savedInstanceState.getInt("qnty")));
}