panic
panic

Reputation: 2098

findFragmentByTag return null fragment

I have this really simple code :

    InboxFragment ibf = new InboxFragment();
    getFragmentManager().beginTransaction().add(ibf, InboxFragment.TAG);
    getFragmentManager().beginTransaction().commit();

    InboxFragment ib2 = (InboxFragment) getFragmentManager().findFragmentByTag(InboxFragment.TAG);

I don't understand why my ib2 is null.

What is the best way to manage different fragments in my activity ? Because I must implement a "Template" system, and each template is represents by a fragment. I have to switch between templates.

Thanks for your help.

Upvotes: 0

Views: 289

Answers (2)

Bö macht Blau
Bö macht Blau

Reputation: 13009

Each time you call getFragmentManager().beginTransaction() a new FragmentTransaction instance is created.

You never commit the first transaction:

getFragmentManager().beginTransaction().add(ibf, InboxFragment.TAG);

but only the second (empty) one:

getFragmentManager().beginTransaction().commit();

Write the following line instead:

getFragmentManager().beginTransaction().add(ibf, InboxFragment.TAG).commit();

In addition to that, the FragmentManager will return null if you call findFragmentByTag() immediately after adding the Fragment, because adding a Fragment will be executed asynchronously by default. You can add the following statement to force execution (but it may result in bad performance):

getFragmentManager().executePendingTransactions();

In your code, you would achieve the same result (initialising ib2) by just writing

ib2 = ibf;

About your "template system": I think it's a good practice to only create what is necessary. Once objects are created, it may be a good idea to keep them around (depends on the app). Retained Fragments may be helpful in your case, but it is recommended to use them mostly for storing data, less for keeping a hold on UI elements.

Upvotes: 1

Shree Krishna
Shree Krishna

Reputation: 8562

See here

After a FragmentTransaction is committed with FragmentTransaction.commit(), it is scheduled to be executed asynchronously on the process's main thread. If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so.

So add this

.executePendingTransactions() after committing to do such operations.

Upvotes: 2

Related Questions