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
Solution 1:
Try checking whether the fragment is already added before replacing
finalFragmentManagerfragmentManager= getSupportFragmentManager();
finalFragmentcontent= fragmentManager.findFragmentById(R.id.content_frame);
if (content == null || !(content instanceof MainFragment)) {
finalFragmentTransactionfragmentTransaction= fragmentManager.beginTransaction();
finalMainFragmentmyFragment=newMainFragment();
fragmentTransaction.replace(R.id.content_frame, myFragment, "MyFragment");
fragmentTransaction.commitAllowingStateLoss();
}
Solution 2:
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
:
FragmentManagerfragmentManager= activity.getFragmentManager();
FragmentlifeFragment= fragmentManager.findFragmentByTag(TAG_FRAGMENT);
if (lifeFragment == null || !(lifeFragment instanceof LifeFragment)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fragmentManager.beginTransaction()
.add(newLifeFragment(), TAG_FRAGMENT)
.commitNowAllowingStateLoss();
}else {
fragmentManager.beginTransaction()
.add(newLifeFragment(), TAG_FRAGMENT)
.commitAllowingStateLoss();
}
}
Post a Comment for "Onstart() On Fragment Is Getting Called Twice In Android"