Android FragmentTransaction commit When?
I am building a tablet app. In this app there is one activity with two fragments. First fragment is a "known" list fragment which is showing a simple one item layout list from a database query, the second fragment shows the details about the selected record (from the list fragment). The think with the second fragment is that its type depends from the records being showed in the list. For example if the records are customers then the selected customer's details are shown, if they are inventory items the selected item's details are shown etc. In order to communicate with the Details Fragment I've created an interface which every detail fragment class implements. The list fragment is "fixed" in the activity from the layout xml. The detail fragment however is created during the activity's creation like this:
super.onCreate(savedInstanceState);
setContentView(R.layout.act_hlpfiles_host);
...
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.laydetailsfragment, FragmentsPool.getHelperFileFragment(501), "recordDetails");
fragmentTransaction.commit();
myDetailsFragment = getFragmentManager().findFragmentByTag("recordDetails");
...
myListFragment = (frg_hlpfiles_lstrecords) getFragmentManager().findFragmentById(R.id.frg_lstrecords);
....
}
The problem with this code is that myDetailsFragment is always null. This is because the fragmentTransaction.commit() does not run immediately but it happens on the main thread the next time that thread is ready (as the android documentation states).
If I create the detail fragment in onStart() and instantiate the list fragment in onCreate everything works ok.
So the question is: How can I be sure that the fragmentTransaction.commit() has commit the transaction so I can do some work with the added fragment? Furthermore is there any way to wait until the commit happens and then continue with the rest of the code?
Try running fragmentManager.executePendingTransactions()
after committing your transaction but before finding by tag and see if that works for you.
In Android API 24 FragmentTransaction
has synchronous .commitNow()
method.
It's in the reference now: https://developer.android.com/reference/android/app/FragmentTransaction.html#commitNow()
On the contrary, .commit()
works asynchronously. It just schedules a commit of the transaction.
I was facing a similar issue.
I think the key learning here is using commitNow() instead of commit() with getSupportFragmentManager. This will disallow the main thread from executing until the fragment has been destroyed. It is imperative when building interfaces and using a shared activity. I should know it had me stumped for a while!
Here is a sample code example: getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.fragment_frame)).commitNow();