我的android异常系列——java.lang.IllegalStateException: commit already called

我的异常系列目录为:http://www.jianshu.com/p/cb10697226ef

出现commit already called这个异常的原因是:同一个FragmentTransaction只能commit一次(调用commit方法),可在它的实现类 BackStackRecord中找到以下代码,每一个BackStackRecord对象都会维护一个布尔变量(mCommitted),当commit后赋值这个变量为true,下次再commit时会检查这个变量,如果是true,则抛出以上异常。commit方法的源码如下:

```java
@Override
public int commit() {
    return commitInternal(false);
}

int commitInternal(boolean allowStateLoss) {
    if (mCommitted) throw new IllegalStateException("commit already called");
    if (FragmentManagerImpl.DEBUG) {
        Log.v(TAG, "Commit: " + this);
        LogWriter logw = new LogWriter(TAG);
        PrintWriter pw = new PrintWriter(logw);
        dump("  ", null, pw, null);
    }
    mCommitted = true;  //这里赋值为true了
    if (mAddToBackStack) {
        mIndex = mManager.allocBackStackIndex(this);
    } else {
        mIndex = -1;
    }
    mManager.enqueueAction(this, allowStateLoss);
    return mIndex;
}
```

综上,我们在使用FragmentTransaction时,需要保证这个对象只调用一次commit,下次commit时需要重新获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值