Can not perform this action after onSaveInstanceState

by Andres Amador / from

I’ve faced this problem sometimes but I’ve never written about it. It’s very interesting because it proves that the Android avoid at all costs lose the state of the activity. This error commonly happens when you try to commit a fragment transaction after the onSaveInstanceState() be called, in other words, when you do it in onPause() or onStop(), depending of the OS version (read here to understand). After the onSaveInstanceState() any new state won’t be saved even the new fragment transaction and the Android doesn’t allow it, throwing an IllegalStateException.

So, if this exception is happening, take a look in what you are doing after onSaveInstanceState()!

Avoiding IllegalStateException

  • Don’t commit a fragment transaction inside the onResume(). If you use Android support library, onResume method isn’t the right place, where to play with fragments. (see Documentation). There are some cases in which this method can be called before the activity’s state has been restored. Do it on onCreate() or onResumeFragments() (the fragment-orientated version of onResume()).
  • Don’t commit a fragment transaction inside AsyncTasks or Worker Threads, because it’s detached of the life cycle, and the state cannot be saved.
  • Prefer commit fragment transactions inside onCreate().
  • Be sure you are commiting the transaction before  the onSaveInstanceState()

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do

Você está comentando utilizando sua conta Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s