Home » Android » findFragmentByTag() always return null – Android

findFragmentByTag() always return null – Android

Posted by: admin May 14, 2020 Leave a comment

Questions:

In my application i have one main activity and several fragments. when user click the back button fragments pops one by one. I want to identify which fragment currently in the back stack. So use to identify fragments by fragment tag name. i used following code segment to get fragment tag name but it always returns null value.

FragmentManager fm = MainActivity.this.getSupportFragmentManager();
String fragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();

please help.

Edit,

replacing fragment with tag,

FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
How to&Answers:

You need to mention the TAG while adding/ replacing it:

ft.replace(R.id.container, newFragment,"fragment_tag_String");

OR

ft.add(R.id.container, newFragment,"fragment_tag_String");

Add the fragment in BackStack as :

ft.addToBackStack("fragment_tag_String");

Then you can reuse it with

getSupportFragmentManager().findFragmentByTag("fragment_tag_String");

Refer :

Edit :

Call getSupportFragmentManager().executePendingTransactions() after doing the transaction

FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
ft.commit();
fm.executePendingTransactions();

Hope it will help you ツ

Answer:

i found my mistake, it is i forgot to add TAG to back stack.

FragmentManager fm = mainActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main_content_fragment, fragment, text);
ft.addToBackStack(text);

And then i can get the current fragment TAG name as follows,

FragmentManager fm = MainActivity.this.getSupportFragmentManager();
String currentFragmentTag = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName();