Android onsaveinstancestate()

时间:2013-01-30 03:38:23

标签: java android

所以我得到了如何使用

的主要想法
  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

但我的问题是,如果这是第一次创建应用程序?然后在...之前没有任何东西存储在捆绑中。如果是这样,那么当我尝试从捆绑中调出一些尚未保存的东西之前我得到什么?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的值是什么?

非常感谢!

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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.
    }