我创建了两个活动A和B.在活动A中,使用onSaveInstanceState方法我保存包值ex(outState.putString(" selectSaveDate",this.CalSelectedDate))并转到Activity B.当我回按活动A的按钮时,在oncreate方法中,bundle值为null。我无法在oncreate方法中获取我保存的值。
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.clear();
Log.i("bundleSave", "tester1" + this.CalSelectedDate);
outState.putString("selectSaveDate", this.CalSelectedDate);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Log.i("todolist", "dsa" + savedInstanceState.getString("selectSaveDate"));
}
}
答案 0 :(得分:0)
您只在OnSaveInstanceState方法的数据包中存储数据,以便在您的活动被销毁和重新创建时(例如,当旋转屏幕时或者当android os可能决定在资源不足时决定终止您的活动时)保留数据)。当您在当前正在执行的活动A之上启动活动B时,A将被置于停止状态(因此,您的A活动不会被销毁)。此外,当你从onStop返回时,下一个被调用的方法是onStart()(技术上onRestart()在onStart()之前被调用,但我发现回调很少被实现。
总之,如果您尝试在当前正在执行的活动之上启动活动之间保持持久数据,则可以将该数据存储在该活动的实例变量中。如果您尝试在应用程序启动之间保留数据,那么您将需要考虑在Android内置的sqllite数据库或Android的SharedPreferences中存储数据。
你还应该对Activity生命周期有一个很好的理解(它很棘手但需要在android中成功编码):
http://developer.android.com/training/basics/activity-lifecycle/index.html
答案 1 :(得分:0)
请尝试覆盖onSaveInstanceState(Bundle savedInstanceState)并将要更改的应用程序状态值写入Bundle参数,如下所示:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "How are you");
// etc.
}
它会传递给onCreate和onRestoreInstanceState,你可以在这里提取这样的值:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
or follow activity life cycle for better understanding.