[Android] IllegalStateException: Can not perform this action after onSaveInstanceState



Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

발생 상황

Fragment의 onStop()에서 transacntion을 실행했을때 위와 같은 Runtime Error가 발생하였다.

supportFragmentManager.beginTransaction()
  .replace(R.id.fragment_container, SomeFragment())
  .commit()


원인

에러 메시지를 보면 onSaveInstanceState 이후에 해당 코드를 실행할 수 없다고 한다.
실제로, host activity가 onSaveInstanceState를 호출한 후에 transaction을 실행하여 오류가 난 것이다.


해결 방법

가장 간단한 방법은 commit() 대신 commitAllowingStateLoss()를 사용하는 것이다.

supportFragmentManager.beginTransaction()
  .replace(R.id.fragment_container, SomeFragment())
  .commitAllowingStateLoss()


단, 권장하는 방법은 아니며 메소드의 정의를 따라가보면 다음과 같은 주석을 확인할 수 있다.

/**
  * Like commit() but allows the commit to be executed after an
  * activity's state is saved.  This is dangerous because the commit can
  * be lost if the activity needs to later be restored from its state, so
  * this should only be used for cases where it is okay for the UI state
  * to change unexpectedly on the user.
  */
  public abstract int commitAllowingStateLoss();

사용자의 행동에 의해 예측하지 못한 UI 상태 변경이 일어나도 괜찮은 경우에만 쓰라는 말이다.


+)

다른 방법으로는 host activity가 resume될 때를 지정하여 transaction을 실행하는 방법이 있는데, Stack Overflow 글에 다양한 해결책이 있으니 참고하길 바란다.



:bookmark: REFERENCE
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState 오류 해결
IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager