shebang
shebang

Reputation: 79

findFragmentByTag() returns null

UPDATE: Just to clarify, show() is an android.app.DialogFragment's method that I didn't overwrote:

public void show(FragmentManager manager, String tag) {
    mDismissed = false;
    mShownByMe = true;
    FragmentTransaction ft = manager.beginTransaction();
    ft.add(this, tag);
    ft.commit();
}

We call the following, where MyDialog extends DialogFragment:

    MyDialog dialog = new MyDialog();
    dialog.show(getFragmentManager(), MyDialog.TAG);

    Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);

But f is always null. Why?

Upvotes: 0

Views: 2291

Answers (3)

TheHebrewHammer
TheHebrewHammer

Reputation: 3138

The issue is simple, DialogFragment.show uses FragmentTransaction.commit which runs asynchronously. So it will only show up on the next iteration of the main thread. To resolve this just add this one line to your code...

MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), MyDialog.TAG);

// Run this line before trying to search for the fragment.
getFragmentManager().executePendingTransactions();

Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);

Upvotes: 5

H Raval
H Raval

Reputation: 1903

to add tag with fragment

Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
    .replace(R.id.container,f,MyDialog.TAG)
    .commit(); 

and to get

Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);

Upvotes: 0

dnkilic
dnkilic

Reputation: 238

FindFragmentByTag returns fragment if found or null otherwise.

Upvotes: -1

Related Questions