Ali Elgazar
Ali Elgazar

Reputation: 777

Android onsaveinstancestate()

so i get the main idea of how to use

  protected void onSaveInstanceState (Bundle outState)

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

also from Saving Android Activity state using Save Instance State

but my problem is what if this was the first time the application is being created? then nothing would have been stored in the bundle before....and if so then when i try to call something out from the bundle that hasn't been saved before what do i get?null? for example i have this in my code

@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);
}

in the FIRST time the application is ever opened what would the value of b be? and after the application has been used once what would the value of b be?

Many thanks!

Upvotes: 0

Views: 5803

Answers (2)

She Smile GM
She Smile GM

Reputation: 1322

in your onCreate() add a condition

 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");
 }

by the way to retrieve data that was saved in your onSaveInstanceState you will override this

 @Override
 protected void onRestoreInstanceState(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
  super.onRestoreInstanceState(savedInstanceState);
}

Upvotes: 3

Kanth
Kanth

Reputation: 6751

You have to check for null always in the onCreate() or in onRestoreInstanceState() like below:

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.
    }

Upvotes: 1

Related Questions