TAGS :Viewed: 7 - Published at: a few seconds ago

[ Why is my custom object not persisted by onSaveInstanceState and onRestoreInstanceState ]

When the activity gets called for the very first time, it is called with an extra in the intent. The extra is received and stored in the data member:

class EditBlindScheduleActivity extends Activity
{
  private BlindSchedule blindSchedule;

  protected void onCreate(Bundle savedInstanceState) 
  {
    ...

    if (savedInstanceState == null) {  // Not recreating, first load.
      blindSchedule = (BlindSchedule) getIntent().getSerializableExtra("blindSchedule");
    }

There is a simple if/else to determine if we have the blindSchedule object or not.

if (blindSchedule == null) {
  setTitle("Create Blind Schedule");
} else {
  setTitle("Edit Blind Schedule");
}

When I load the activity for the first time, indeed, the title is "Edit Blind Schedule", meaning there is a blindSchedule object.

Unfortunately, when I rotate the screen twice the title reads "Create Blind Schedule", meaning the blindSchedule object is null and has failed to be persisted.

Why is my blindSchedule object not being persisted, and what can I do about it?

Full code follows:

public class EditBlindScheduleActivity extends Activity {

  private BlindSchedule blindSchedule;

  Boolean creating;  // Creating or updating?

  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_blind_schedule);

    if (savedInstanceState == null) {  // Not recreating, first load.
      blindSchedule = (BlindSchedule) getIntent().getSerializableExtra("blindSchedule");
    }

    if (blindSchedule == null) {
      creating = true;
      setTitle("Create Blind Schedule");
    } else {
      creating = false;
      setTitle("Edit Blind Schedule");
    }
  }

  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    blindSchedule = (BlindSchedule) savedInstanceState.getSerializable("blindSchedule");
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("blindSchedule", blindSchedule);
  }

Answer 1


You need to retrieve the saved custom object in onCreate in your case.

According to Official Documentation

onRestoreInstanceState is called after onStart by which time your setTitle has already been called.

Add an else part to the if (savedInstanceState == null) and retrieve blindSchedule in there same way as you do for your getIntent

if (savedInstanceState == null) 
{  // Not recreating, first load.
  blindSchedule = (BlindSchedule) getIntent().getSerializableExtra("blindSchedule");
}
else
{
  blindSchedule = (BlindSchedule) savedInstanceState.getSerializableExtra("blindSchedule");
}