在一个EditText输入框中输入字符,activity被destroy之前通过onSaveInstanceState()
保存输入字符,当重新create这个activity时,onCreate(Bundle)
的Bundle参数却是null,不清楚问题出在哪?activity的代码如下:
package com.example.TestSaveInstanceState;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.widget.EditText;
public class MyActivity extends Activity {
static final String STATE_KEY = "etInputState";
EditText etInput;
static final String MYTAG = "mytag";
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etInput = (EditText)findViewById(R.id.etInput);
if(savedInstanceState != null) {
Log.w(MYTAG, savedInstanceState.getString(STATE_KEY));
etInput.setText(savedInstanceState.getString(STATE_KEY));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String _s = etInput.getText().toString();
if(_s != null) {
outState.putString(STATE_KEY, _s);
Log.w(MYTAG, "instance state = " + _s);
}
}
}
我想这不是你代码的问题,
onSaveInstanceState()
是在系统
需要recreate这个Activity的时候才会去调用他,比如屏幕由竖屏切换到横屏,改变了语言等,而不是人为地finish/create一个Activity,如果你想达到你想要的目的,要在onPause方法中保存当前Activity中的状态。这是官方文档的解释:To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity isdestroyed unexpectedly
. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.