Malwinder Singh
Malwinder Singh

Reputation: 7060

Retrieving Fragment by using Fragment Tag

I am getting NullPointerException when retrieving a Fragment by its tag defined during its addition via SupportFragmentManager.

Here's the code:

 FragmentOne fragmentOne = new FragmentOne();
    getSupportFragmentManager().beginTransaction().add(R.id.container, fragmentOne,FRAGMENT_ONE_TAG).addToBackStack(null).commit();

    FragmentOne fragmentOneInstance = (FragmentOne) getSupportFragmentManager().findFragmentByTag(FRAGMENT_ONE_TAG);
    Log.i("Fragment One Instance: ", fragmentOneInstance.getTag());

Error report:

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.demo.fragment/com.ms.android.demo.fragment.MainActivity}: java.lang.NullPointerException

Upvotes: 0

Views: 38

Answers (2)

mmlooloo
mmlooloo

Reputation: 18977

Fragment transactions are asynchronous task and when you commit, it dose not mean it is added immediately so you must call executePendingTransactions() if you want the transaction happens right away

FragmentOne fragmentOne = new FragmentOne();
    getSupportFragmentManager().beginTransaction().add(R.id.container, fragmentOne,FRAGMENT_ONE_TAG).addToBackStack(null).commit();

getSupportFragmentManager().executePendingTransactions();

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157457

you have to wait until the transaction is executed. You can't run it immediately it after you add the fragment to the transaction.

.commit(); is an asynchronous call.

From the documentation

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

As a test, you can run executePendingTransactions () to execute immediately any pending operation.

Upvotes: 1

Related Questions