ARP
ARP

Reputation: 613

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 !!!

Upvotes: 3

Views: 4095

Answers (2)

jiar wang
jiar wang

Reputation: 360

commit or commitAllowingStateLoss is an asynchronous excute, so fragmentManager.findFragmentById(R.id.content_frame); will a null before first commit finished, that will cause replace called twice. you can debug onStart function, and see the hashCode of current Fragment object.

I replace commit to commitNow:

FragmentManager fragmentManager = activity.getFragmentManager();
        Fragment lifeFragment = fragmentManager.findFragmentByTag(TAG_FRAGMENT);
        if (lifeFragment == null || !(lifeFragment instanceof LifeFragment)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fragmentManager.beginTransaction()
                        .add(new LifeFragment(), TAG_FRAGMENT)
                        .commitNowAllowingStateLoss();
            }else {
                fragmentManager.beginTransaction()
                        .add(new LifeFragment(), TAG_FRAGMENT)
                        .commitAllowingStateLoss();
            }
        }

Upvotes: 0

Yaroslav Mytkalyk
Yaroslav Mytkalyk

Reputation: 17105

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();
}

Upvotes: 4

Related Questions