针对illegalstateException OnloadFinished

本文解析了在onLoadFinished()中提交FragmentTransaction导致的异常原因,包括状态丢失风险及背景线程通知问题,并提供了最佳解决方案。

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

Here is some background to help anyone who encounters this exception.

The exception is thrown because the framework doesn't allow to commit a fragment transaction in the same call stack as onLoadFinished(). This behavior provides a protection against state lose, because loaders are normally based on background threads (AsyncTaskLoader) which can finish their work and notify back anytime.

There could be two potential issues: 1. The framework already saved the state (for example because of orientation change) of the fragments in the fragment manager when the call to onLoadFinished() is performed. Committing a transaction in this context will result in state lose because this late transaction is not included in the saved state. 2. The framework has not finished restoring from a previous saved state. Here, the transaction comes too early before the state has been restored.

There are two problems with Maria's answer above: 1. calling runOnUiThread() doesn't help because onLoadFinished() is called on the UI thread which means the call to runOnUiThread() will be called in the same call stack which will raise the exception. The documentation says: "If the current thread is the UI thread, then the action is executed immediately." 2. Even if the call (here DialogFragment.show()) hadn't been done in the same call stack) for example by:

public void onLoadFinished(Loader<Map<String, Integer>> arg0,
                            Map<String, Integer> result) {
    if (result == null) {

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                netEMessage();
            }
        });
    } 
}

the risks above would still exist.

The best solution to this issue is to move the fragment transaction to a different place in the flow while ensuring issues 1. and 2. above cannot happen. For example, performing the transaction from Activity.onPostResume().

Good luck!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值