Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android fragments - findFragmentByTag always returns null

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

like image 627
maxdownunder Avatar asked Aug 20 '13 09:08

maxdownunder


Video Answer


1 Answers

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

like image 192
Pravin Avatar answered Oct 13 '22 10:10

Pravin