Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onstart() on Fragment is getting called twice in android

I have an activity on which I have one fragment. In onStart() of fragment I have all network calls.When app comes from background onStart() is getting called twice and all network are called twice and I also observed that onCreate()is called only once.Has some one faced such issue.Please help me out. My code for fragment transaction is as below

 MainFragment myFragment = new MainFragment ();
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.content_frame, myFragment, "MyFragment");
                fragmentTransaction.commitAllowingStateLoss();

Thanks in advance !!!

like image 870
Pradeep kumar AR Avatar asked Nov 20 '25 01:11

Pradeep kumar AR


1 Answers

Try checking whether the fragment is already added before replacing

final FragmentManager fragmentManager = getSupportFragmentManager();
final Fragment content = fragmentManager.findFragmentById(R.id.content_frame);
if (content == null || !(content instanceof MainFragment)) {
    final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    final MainFragment myFragment = new MainFragment();
    fragmentTransaction.replace(R.id.content_frame, myFragment, "MyFragment");
    fragmentTransaction.commitAllowingStateLoss();
}
like image 131
Yaroslav Mytkalyk Avatar answered Nov 22 '25 03:11

Yaroslav Mytkalyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!