Kirill Zotov
Kirill Zotov

Reputation: 571

Get fragment from backstack

Hardly can't get fragment from backstack, even start thinking of keeping in in singleton which is probably bad. Saved to backstack like this and all time try to get it by tag or something gives me error.

Fragment fragment = UserProfileFragment.newInstance(null);
                        FragmentTransaction trans = getFragmentManager().beginTransaction();
                        trans.replace(FRAGMENT_PLACE_RESOURCES, fragment);
                        trans.addToBackStack("profile");
                        trans.commit();

It just return me null here so I can't use this fragment. No logs.

Fragment fragment2 = getFragmentManager().findFragmentByTag("profile");

Upvotes: 3

Views: 7863

Answers (1)

Gopal Singh Sirvi
Gopal Singh Sirvi

Reputation: 4649

getFragmentManager().findFragmentByTag("tag")

is only used when you have added a fragment with specific tag for e.g.

fragmentTransaction.add(R.id.order_container,mProfileFragment,"profile");

or

fragmentTransaction.replace(R.id.order_container,mProfileFragment,"sometag");

Then you will be able to find this fragment by the tag.

In your case you are adding a transaction to backstack so you will not be able to find that fragment by tag. You just adding a transaction to backstack thats it not a fragment. And also your fragment was removed from the activity and destroyed so you have to revert the transaction by popping backstack instead of finding that fragment by tag. You have to call

getFragmentManager().popBackStack("profile");

to get that fragment back to the activity and make it visible on screen.

Upvotes: 4

Related Questions