【问题标题】:Android: saving / restoring instance stateAndroid:保存/恢复实例状态
【发布时间】:2013-08-15 04:21:24
【问题描述】:

完全卡住保存和恢复活动的实例状态。这是我所拥有的:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register1);

    context = this;

    input_first_name = (EditText) findViewById(R.id.first_name);
    input_last_name = (EditText) findViewById(R.id.last_name);
    input_email = (EditText) findViewById(R.id.register_email);
    input_password = (EditText) findViewById(R.id.register_password);
    input_cell = (EditText) findViewById(R.id.register_cell);

    if (savedInstanceState != null) {
        System.err.println(savedInstanceState.getString("first_name"));
        input_first_name.setText(savedInstanceState.getString("first_name"));
        input_last_name.setText(savedInstanceState.getString("last_name"));
        input_email.setText(savedInstanceState.getString("email"));
        input_password.setText(savedInstanceState.getString("password"));
        input_cell.setText(savedInstanceState.getString("cell"));
    }
    ...
}

protected void onSaveInstanceState(Bundle b) {
    super.onSaveInstanceState(b);
    System.err.println("save called");

    b.putString("first_name", first_name);
    b.putString("last_name", last_name );
    b.putString("email", email);
    b.putString("password", password);
    b.putString("cell", cell);
}

protected void onRestoreInstanceState(Bundle b) {
    System.err.println(b.getString("first_name"));
    input_first_name.setText(b.getString("first_name"));
    input_last_name.setText(b.getString("last_name"));
    input_email.setText(b.getString("email"));
    input_password.setText(b.getString("password"));
    input_cell.setText(b.getString("cell"));
}

我得到了“保存调用”的输出,所以我认为我的包已正确保存。但是,当我回到活动中时,我从未看到任何输出。有人看到我做错了吗?谢谢!

【问题讨论】:

  • 嗯,首先你应该使用更安全的“get”方法,指定一个默认值(saveState.getString("abc", "default"))。
  • 您没有在任何地方设置变量 (first_name, ...) 的值
  • 只有在重新创建Activity时才会调用onRestoreInstanceState方法。你是如何模拟销毁 Activity 的?
  • 另外,使用if (savedInstanceState != null)onCreate(Bundle) 中检索Bundle 值然后在onRestoreInstanceState(Bundle) 中再次 是系统滥用。
  • @Mohamed_AbdAllah 抱歉,这些设置在调用下一个意图的 onclick 侦听器中。只是试图将代码量保持在最低限度,但你是对的,我没有发布。但是,它们已经设置好了。

标签: java android


【解决方案1】:

我真的看不出有什么问题 添加@Override 以确保它在您的类中调用该函数,而不是在超类中调用该函数

如下:

@Override
protected void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
System.err.println("save called");

b.putString("first_name", first_name);
b.putString("last_name", last_name );
b.putString("email", email);
b.putString("password", password);
b.putString("cell", cell);
}

【讨论】:

  • @usr55410 如果您还没有解决问题,您可以使用粘贴箱并向我展示您的更多代码吗? www.pastebin.com
【解决方案2】:

尝试this solution 以确保您正确使用onRestoreInstanceState

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2013-04-04
    • 2011-07-23
    • 2014-04-25
    • 2014-01-11
    • 1970-01-01
    相关资源
    最近更新 更多