Sunday, September 11, 2011

onSaveInstanceState() and onRestoreInstanceState()

As mentioned in the article "Activity will be re-started when screen orientation changed", the activity will be destroyed and re-created once screen orientation changed.



We can call onSaveInstanceState() to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).



example:

onSaveInstanceState() and onRestoreInstanceState()


package com.exercise.AndroidSavedInstanceState;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidSavedInstanceStateActivity extends Activity {

EditText edit;
Button update;
TextView text;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

edit = (EditText)findViewById(R.id.edit);
update = (Button)findViewById(R.id.update);
text = (TextView)findViewById(R.id.text);

update.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
text.setText(edit.getText().toString());
}});
}

@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putString("TEXT", (String)text.getText());
}

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

}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/update"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Update"
/>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


Without onSaveInstanceState() and onRestoreInstanceState(), TextView text will be cleared everytime the screen orientation changed.

Notice that if the activity finished completely, the state will not be saved.

Next:
- More on onSaveInstanceState() and onRestoreInstanceState()



1 comment:

Anonymous said...

its not working for me