Android fragments - findFragmentByTag always returns null

18,496

In your code you haven't mentioned tag in replace method So,
Use this structure of replace method of fragment

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

Refer this link for more information. fragment replace with tag name

Share:
18,496
maxdownunder
Author by

maxdownunder

Updated on July 23, 2022

Comments

  • maxdownunder
    maxdownunder almost 2 years

    I've had a look around and found a couple of questions with a similar topic, but nothing that helped in my case. I'm trying to access an existing active fragment using getSupportFragmentManager().findFragmentByTag(TAG), but it always returns null. Replies on similar questions suggested that it takes a while for the commit to be executed, so calling findFragmentByTag would return null if called too early. I've tried two things:

    • add getSupportFragmentManager().executePendingTransactions()
      immediately after the commit, but still get null.
    • added a button... pressing this after the activity has been created, the fragment registered and the view displayed should leave the system enough time to commit. But i still get null.

    Here's my activity:

    public class MainActivity extends ActionBarActivity {
    
    private static final String F_SETTINGS = "f_settings";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_main);
    
        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                debug();
            }
        });
    
        if (savedInstanceState == null) {
            FSettings newFragment = new FSettings();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.container, newFragment);
            ft.addToBackStack(F_SETTINGS);
            ft.commit();
            // getSupportFragmentManager().executePendingTransactions();
            //// Activating this did not make any difference...
        }
    
        debug();
    }
    
    private void debug() {
        String txt = "null";
        Fragment frag = getSupportFragmentManager().findFragmentByTag(F_SETTINGS);
        if (frag != null) {
            txt = frag.toString();
        }
        Log.i("Testing", txt);
    }
    

    }

    What am I doing wrong here? Cheers, Max

  • maxdownunder
    maxdownunder almost 11 years
    Oh dear, you wouldn't believe how long I stared at the code to figure whats wrong... thanks, works now.
  • Dr.jacky
    Dr.jacky almost 10 years
    Please see my related question: stackoverflow.com/questions/24833912/…
  • Akshay kumar
    Akshay kumar over 4 years
    Thank you so much bro.