Android Honeycomb: How to determine when FragmentTrancaction.commit() has finished?
I had this simple piece of code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//...
NetworkWorker networkFragment = NetworkWorker.createInstance(null);
fragmentTransaction.add(networkFragment, NETWORK);
//...
fragmentTransaction.commit();
networkFragment.startURLRequest("test");
}
which crashed when I called getActivity()
in my startURLRequest()
routine.
As soon as I've moved the startURLRequest()
call to onStart()
it worked fine.
So I googled a bit and found this:
Calling commit() does not perform the transaction immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon as the thread is able to do so. If necessary, however, you may call executePendingTransactions() from your UI thread to immediately execute transactions submitted by commit(). Doing so is usually not necessary unless the transaction is a dependency for jobs in other threads. [AndDev guide]
Now, my question is... is it really advisable to use this executePendingTransactions()
or will this hold some traps? Is there another way to determine if the transaction have finished? Just guessing that they might be finished in开发者_C百科 the Activity's next routine doesn't seem satisfying.
Kind regards, jellyfish
Maybe you are thinking about this the wrong way. Rather than calling startURLRequest
on your fragment from the activity why not call startURLRequest
in your fragment's onAttach
, onCreate
etc. methods as at these points you know that the fragment is attached to the activity and getActivity() will succeed.
It does seem to me that the fragment should be deciding on when to call startURLRequest
and not the activity. Otherwise from your activity would have to test to ensure the fragment is associated with a fragment.
One would assume that the commit is finished when all fragments in the transaction have returned from onResume (for fragments being added).
精彩评论