John Moffitt John Moffitt - 15 days ago 6
Android Question

GetFragmentManager.findFragmentByTag() returns null

getFragmentManager().beginTransaction()
.replace(R.id.graph_fragment_holder, new GraphFragment(), "GRAPH_FRAGMENT")
.commit();

getFragmentManager().beginTransaction()
.replace(R.id.list_fragment_holder, new ListFragment(), "LIST_FRAGMENT")
.commit();

//getFragmentManager().executePendingTransactions();

GraphFragment graphFragment = (GraphFragment) getFragmentManager().findFragmentByTag("GRAPH_FRAGMENT");
graphFragment.setData(data);

ListFragment listFragment = (ListFragment) getFragmentManager().findFragmentByTag("LIST_FRAGMENT");
listFragment.setData(data);


I've supplied a tag so I'm not sure why
findFragmentByTag()
returns
null
.

What I've tried from reading other questions:


  1. this.setRetainInstance(true)
    in the
    oncreate
    of both
    fragments
    .

  2. Both
    fragment
    constructors are empty
    public fragmentName(){}
    .

  3. tried
    executePendingTransactions
    after adding the
    fragments
    .

  4. tried
    add
    instead of
    replace
    on the
    fragments
    (edited)


Answer

I was having the same problem of findFragmentByTag() always returning null.

Eventually I tracked it down, I was overriding onSaveInstanceState() in my Activity but not calling super. As soon as I fixed that findFragmentByTag() returned the Fragment as expected.

Comments