Android - 解决onSaveInstanceState的Bug

解决onSaveInstanceState的Bug


本文地址:http://blog.csdn.net/caroline_wendy


Bug:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
     at android.support.v4.app.FragmentManagerImpl.checkStateLoss(Unknown Source)
     at android.support.v4.app.FragmentManagerImpl.enqueueAction(Unknown Source)
     at android.support.v4.app.BackStackRecord.commitInternal(Unknown Source)
     at android.support.v4.app.BackStackRecord.commit(Unknown Source)
     at android.support.v4.app.FragmentTabHost.onAttachedToWindow(Unknown Source)
     at android.view.View.dispatchAttachedToWindow(View.java:12618)
     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2467)
     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2467)
     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2467)
     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2467)
     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2467)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1262)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1045)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5908)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:780)
     at android.view.Choreographer.doCallbacks(Choreographer.java:593)
     at android.view.Choreographer.doFrame(Choreographer.java:562)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:766)
     at android.os.Handler.handleCallback(Handler.java:733)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:136)
     at android.app.ActivityThread.main(ActivityThread.java:5336)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
     at dalvik.system.NativeStart.main(Native Method)


参考:

解决:
重载onSaveInstanceState()中,不调用super()方法,因为调用super方法,在API level大于11时,可能导致崩溃
@Override
protected void onSaveInstanceState(Bundle outState) {
    //No call for super(). Bug on API Level > 11.
//        super.onSaveInstanceState(outState);
}

onSaveInstanceState()方法的作用: 
onSaveInstanceState的调用遵循原则,即当系统“未经用户许可”时销毁activity,则onSaveInstanceState会被系统调用。
这是系统的责任,因为它必须要提供一个机会让用户保存数据。

super.onSaveInstanceState(outState):
活动本身会在bundle中存入一些值,例如fragments的状态,如果没有调用super方法,这些值不会被保存,但也不会使程序崩溃。


技术分享





郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。