Complete FragmentTransaction with commit()

ID

java.android_transaction_commit

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:404, android, reliability

Description

Reports FragmentTransaction variables obtained via beginTransaction() that are never completed with a commit call (commit(), commitAllowingStateLoss(), commitNow(), or commitNowAllowingStateLoss()) within the same method body. An uncommitted transaction has no effect and is silently discarded, making it a common source of "why doesn’t my fragment show?" bugs.

Rationale

A FragmentTransaction is a batch of fragment operations (add, remove, replace, etc.) that must be finalized by one of the commit methods. Without a commit, the operations are never applied to the FragmentManager.

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new MyFragment());
// Bug: ft is never committed -- the replace has no effect

Remediation

Always call one of the commit methods after building the transaction:

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, new MyFragment());
ft.commit();

Use commitAllowingStateLoss() only when state loss is acceptable (e.g., best-effort UI updates). Use commitNow() when the transaction must be applied synchronously.