Sobes.tech
Junior — Middle

What are the differences between using commit(), commitNow(), and commitAllowingStateLoss() when managing transactions in FragmentManager?

sobes.tech AI

Answer from AI

In FragmentManager, there are several commit methods that differ in timing and conditions:

  • commit() — queues the transaction for execution. It runs asynchronously, in the main thread, after the system processes current tasks. This is safe and recommended.

  • commitNow() — executes the transaction immediately, synchronously. Used when changes need to be applied right away, such as during UI initialization. Cannot be used if the transaction is added to the back stack.

  • commitAllowingStateLoss() — similar to commit(), but allows executing the transaction even if the activity state has already been saved (e.g., during orientation change). It may lead to loss of changes during state restoration, so use with caution.

Example:

fragmentManager.beginTransaction()
    .replace(R.id.container, new MyFragment())
    .commit(); // Asynchronous

fragmentManager.beginTransaction()
    .replace(R.id.container, new MyFragment())
    .commitNow(); // Synchronous

fragmentManager.beginTransaction()
    .replace(R.id.container, new MyFragment())
    .commitAllowingStateLoss(); // Can be called after onSaveInstanceState

This provides flexibility in managing fragment transactions.

What are the differences between using commit()… - sobes.tech