My activity may show a DialogFragment
when it resumes. As suggested in this fragment transactions tutorial , I'm doing that in onResumeFragments()
to avoid the dreaded IllegalStateException: Can not perform this action after onSaveInstanceState
. For the most part, all is well.
But my activity also has an OnSharedPreferenceChangeListener
that restarts the activity when a certain preference is changed. The preference change that triggers the listener is caused by making a selection in a Spinner
. If the activity restarts itself by calling recreate()
, I get the IllegalStateException
. But if the activity restarts itself like this, there's no problem:
finish();
final Intent intent = new Intent(StartActivity.this, StartActivity.class);
startActivity(intent);
I'd prefer to use recreate()
because I want my instance state to be saved. Why would this result in onResumeFragments()
being called after onSaveInstanceState()
?
Well, I feel kind of dumb. I had a fragment that called setRetainInstance(true)
but cached a reference to its activity in onCreate(...)
instead of onActivityCreated(...)
. The fragment was attempting to display a dialog using the old activity. (To be more precise, the activity was indirectly calling a method on the fragment from onResumeFragments()
.) Pretty messy. I should probably rethink the whole relationship between the fragment and the activity.
Edit: I've since discovered another way this can happen that isn't my fault. If the lock screen is shown over a running activity, onSaveInstanceState()
is called. But when the lock screen is dismissed, onRestoreInstanceState()
is not called between onResume()
and onResumeFragments()
. This bug is at least five years old. Thanks, Google.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.