【问题标题】:state of app after 2 rotations2 次旋转后的应用程序状态
【发布时间】:2017-11-25 13:56:00
【问题描述】:

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

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

这是我的代码

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

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

【问题讨论】:

    标签: android screen-rotation onsaveinstancestate onrestoreinstancestate


    【解决方案1】:

    您使用一个名为 cowQnty 的变量将值存储在 onSaveInstanceState 的捆绑包中作为 outState.putInt("qnty", cowQnty);,然后当您在 onRestoreInstanceState 中恢复它时,您只需设置 TextView 的value 为检索到的值,并且不更新 cowQnty 的值。

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

    首先,如果cowQnty 不是一个可观的数量并且您不介意使用一点内存,请将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")));
    }
    

    【讨论】:

    • 对我感到羞耻 :( 我一直在思考和思考……它是绝对的。清楚 >> 当我恢复我的状态时,我必须每次设置我的数量 #ahhhhhh 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多