Android can not perform this action after onSaveInstanceState 问题解决

本文探讨了在Android开发中,当MainActivity执行onSaveInstanceState后修改Fragment导致的Crash问题。详细介绍了commit与commitAllowingStateLoss的区别,并给出了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天遇到了一个这样的问题,我写了一个MainActivity,里面有一个NavigationDrawer,其中的内容自然是使用的Fragment,当我在MainActivity上弹出一个Dialog样式的Activity并且这个Activity将要关闭的时候,程序会Crash掉,报出一个 java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState的错误,通过十几个Log连续输出跟踪,发现时在修改Fragment的commit的时候出现了异常,查看开发者文档,是这样写的

public abstract int commit ()
Added in API level 11

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

A transaction can only be committed with this method prior to its containing activity saving its state. If the commit is attempted after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss() for situations where it may be okay to lose the commit.

Returns
  • Returns the identifier of this transaction's back stack entry, if addToBackStack(String) had been called. Otherwise, returns a negative number.

首先,他说commit不是立即执行,而是当主线程在下一次准备好的时候进行修改,也就是说,这个函数只是把请求放到队列中去。注意中间的部分,他说commit操作必须在父容器saving state之前,因为当父容器saving state,意味着父容器可能会被销毁,这个时候这个commit可能会变成无效的。

回过头来看我们的错误,应该就是这个问题,所以下面的的解决方式就是使用commitAllowingStateLoss()方法,我们再看一下这个方法的介绍

public abstract int commitAllowingStateLoss ()
Added in API level 11

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.

很明显这就是我们想要的方法,允许在MainActivity执行onSaveInstanceState后进行Fragment修改。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值