Sunday, 4 December 2011

Android Saved Instance State Bundle

Hi,
Normally when the device is tilted(i.e. screen orientation is changed) the activity is restarted.Whole activity is destroyed and recreated.So when activity is destroyed ,we need to save the state of activity.This can be done using the onSaveInstanceState and onRestoreInstanceState.


public class SavedInstanceActivity extends Activity {
TextView main_text;
Button update_button;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        main_text=(TextView)findViewById(R.id.main_text);
        update_button=(Button)findViewById(R.id.press_saved);
        update_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
main_text.setText("SAVED INSTANCE STATE");
}
});
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("SAVED", main_text.getText().toString());
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    main_text.setText(savedInstanceState.getString("SAVED"));
    }
}

Like as you see in the above example if we had not used the onSavedInstanceState() then whole activty would have been recreated and textview would have been blank again.

Click to download the full source code: SOURCE CODE