19

I read that if we need to create fragment immediately, we have to call executePendingTransactions() method on FragmentManager. Well, that's what I'm trying to do. Like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.add(R.layout.fragmentContainer, new MyFragment);
    fragmentTransaction.commit();
    fragmentManager.executePendingTransactions();

    foo(); // It is called before MyFragment's onCreateView()
}

I'd like to know why foo() method is called BEFORE MyFragment's onCreateView(). As you see, I'm calling executePendingTransactions() in UI Thread as it should be. I'm not messing here with threads at all.

Piotr Chojnacki
  • 6,837
  • 5
  • 34
  • 65
  • Can you attach a boolean to execute pending txns like this `boolean val = fragmentManager.executePendingTransactions();` and see what it yields once foo is called while debugging. – Vrashabh Irde Jun 21 '13 at 08:49
  • Hi, is there any news on this issue? I'm facing same problem and cannot find the solution. If you've solved it, can you share the solution, please? – Haspemulator Aug 28 '13 at 11:30
  • @Haspemulator Unfortunately not - I finally decided to use completely different approach. – Piotr Chojnacki Aug 29 '13 at 05:59
  • 1
    I'm still interessted why it works in the onStart and not in the onCreate. Anyone? – user1879408 Dec 22 '15 at 13:08

1 Answers1

18

I ran into the same issue and I found that if I ran the same fragmentTransaction code from within the onStart method, the execution worked as expected. I do not know enough about the Android view lifecycle to know why this is the case though.

public void onStart() {
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.add(R.layout.fragmentContainer, new MyFragment);
    fragmentTransaction.commit();
    fragmentManager.executePendingTransactions();

    foo(); // Should now work correctly
}
ssawchenko
  • 1,198
  • 1
  • 13
  • 24
  • 1
    Thanks! I only want to add one useful feature - use onPostCreate() instead of onStart() to avoid fragment creation every time onStart() is called. Cheers! – Alexander Krol Aug 15 '17 at 13:25
  • Wow I can't believe this worked. Android is really confusing edit: whaaaa no this onStart is called in situations where oncreate isn't, like returning from a camera intent... – pete Aug 12 '20 at 07:45