因此,我了解了如何使用
protected void onSaveInstanceState (Bundle outState)http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
也来自Saving Android Activity state using Save Instance State
但我的问题是,如果这是第一次创建应用程序怎么办?如果是这样的话,当我试图从包中调用之前还没有保存的东西时,我会得到什么呢? before....and?例如,我的代码中包含以下内容
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String [] b=savedInstanceState.getStringArray("MyArray");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
String [] a={"haha"};
savedInstanceState.putStringArray("MyArray", a);
}在第一次打开应用程序时,b的值是什么?在应用程序被使用一次之后,b的值是什么?
非常感谢!
发布于 2013-01-30 11:43:54
在onCreate()中添加一个条件
if(savedInstanceState==null){
//meaning no data has been saved yet or this is your first time to run the activity. Most likely you initialize data here.
}else{
String [] b=savedInstanceState.getStringArray("MyArray");
}顺便说一下,为了检索保存在onSaveInstanceState中的数据,您将覆盖这个
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
}发布于 2013-01-30 11:42:18
您必须始终在onCreate()或onRestoreInstanceState()中检查null,如下所示:
String [] b = new String[arraysize];
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
b = savedInstanceState.getStringArray("MyArray");
// Do here for resetting your values which means state before the changes occured.
}
else{
default..
}
Here you do general things.
}https://stackoverflow.com/questions/14596272
复制相似问题