Very simple code, but got error “Activity has been destroyed” when use Fragment

前端 未结 9 1129
误落风尘
误落风尘 2020-12-05 14:15

I made a very simple Activity which shows a simple ListFragment like below:

My Activity:

public class MyActivity ex         


        
相关标签:
9条回答
  • 2020-12-05 15:00

    I also faced a similar problem.
    I realized that this happened because the activity was being destroyed while the FragmentTransaction was about to get .commit().

    A solution to this was to check whether the Activity.isFinishing() is true or not.

    if (!isFinishing()) {
      FragmentTransaction ft = getSupportFragmentManager()
         .beginTransaction();
      ft.replace(SOME_RES_ID, myFragmentInstance);
      ft.commit();
    }
    
    0 讨论(0)
  • 2020-12-05 15:03

    what i did is immediately after commit i call

    fragmentManager.executePendingTransactions();

    and never try to commit after onpause() called

    Read this Artical Fragment Transactions & Activity State Loss

    0 讨论(0)
  • 2020-12-05 15:04

    To give an explanation:

    The framework creates the Activity and calls Activity.onCreate().

    Activity.onCreate() will somehow attach to the FragmentManager to let it know about the hosting activity. Activity.onDestroy() will unregister it again.

    Now, you extend Activity and override onCreate(). You make calls to FragmentManager without calling through toActivity.onCreate(). The whole registration logic explained above is not executed. The FragmentManager therefore does not know anything about the activity and assumes it has already been destroyed and generates the exception with the misleading error message.

    0 讨论(0)
提交回复
热议问题