【问题标题】:Caused by java.lang.IllegalStateException Can not perform this action after onSaveInstanceState由 java.lang.IllegalStateException 引起 onSaveInstanceState 后无法执行此操作
【发布时间】:2021-05-04 18:26:16
【问题描述】:

我有一个活动和该活动中的一个片段。片段在活动onCreate() 中加载。

if (!supportFragmentManager.isDestroyed) {
    val fragmentTransaction = this.supportFragmentManager.beginTransaction()
    fragmentTransaction.replace(R.id.containerLayout, fragment).commit()
}

在 Fragment 内部,我正在执行 API 调用,当收到结果时,Activity 会收到回调,并将结果从 Activity 传递给 Fragment。

问题是当我加载此活动时,如果我按下设备最近按钮,API 仍在调用中,那么应用程序崩溃并显示以下异常。

Caused by java.lang.IllegalStateException Can not perform this action after onSaveInstanceState

我知道问题是在调用onSaveInstanceState 之后片段尝试提交。但这是怎么发生的,我不清楚。我也通过了article。它说三点作为解决方案。

  1. 在我已经在做的 onCreate() 中提交片段。
  2. 在不适用于我的 onPostExecute() 中不提交。
  3. 仅将 commitAllowingStateLoss() 用作最后的手段。

我是否需要将commit() 更改为commitAllowingStateLoss()?当我浏览文档时,我也觉得不安全。有人可以向我建议正确的方法吗?

【问题讨论】:

    标签: android kotlin android-fragments


    【解决方案1】:

    我没有使用 commitAllowingStateLoss()。我把代码写成:

    var isAnException: Boolean = false
    
    try {
        if (!supportFragmentManager.isDestroyed) {
            val fragmentTransaction = this.supportFragmentManager.beginTransaction()
            fragmentTransaction.replace(R.id.containerLayout, fragment).commit()
        }
    } catch (exception: IllegalStateException) {
       isAnException = true
    }
    

    在我的活动的 onResume() 中,我添加了以下代码以使片段在从最近获取的片段中工作。

    override fun onResume() {
       if (isAnException) {
          isAnException = false
          //fragment load and set the views
       }
       super.onResume()
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      相关资源
      最近更新 更多