Android:保存/恢复实例状态

时间:2013-08-14 19:47:09

标签: java android

完全停止保存并恢复活动的实例状态。这就是我所拥有的:

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

我正在获取“save called”的输出,所以我认为我的包已正确保存。但是,当我回到活动中时,我从未看到任何输出。有谁看到我做错了什么?谢谢!

2 个答案:

答案 0 :(得分:0)

我真的没有看错 添加@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);
}

答案 1 :(得分:0)

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