0

所以我明白了如何使用的主要思想

  protected void onSaveInstanceState (Bundle outState)

http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

也来自使用 Save Instance State 保存 Android Activity 状态

但我的问题是,如果这是第一次创建应用程序怎么办?那么之前任何东西都不会存储在捆绑包中......如果是这样,那么当我尝试从捆绑包中调出之前尚未保存的东西时,我会得到什么?null?例如我的代码中有这个

@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 的值是多少?

非常感谢!

4

2 回答 2

3

在你的 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-30T03:43:53.700 回答
1

您必须始终在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.
    }
于 2013-01-30T03:42:17.990 回答