0

我已经阅读了有关该主题的文档,在前台活动将被销毁之前保存状态...

现在一切都很好(在设备旋转之后),但是当我在旋转后再次旋转我的设备时,我会再次丢失我的数据:(

这是我的代码

@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));

谁能告诉我我是否接近解决方案?

4

1 回答 1

1

您使用一个名为的变量cowQnty来存储该值,然后将该值保存在您的onSaveInstanceStateas的捆绑包中outState.putInt("qnty", cowQnty);,然后当您将其还原时,onRestoreInstanceState您只需将TextView's 的值设置为检索到的值,而不更新 for 的值cowQnty

您如何期望再次保存一个空字段?有两种解决方案;

首先,如果cowQnty不是一个相当大的数量并且您不介意使用一点 RAM,请创建cowQnty一个static字段,它将持久保存数据,而根本不需要将其保存在 aBundle中。

其次,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")));
}
于 2017-11-25T14:04:50.877 回答