Reputation: 6449
My application usually add and then remove the same fragment many times. Below is how I do this:
Add fragment
if (mHomeFragment == null)
{
mHomeFragment = new HomeFragment();
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
getSupportFragmentManager().beginTransaction().add(R.id.dummy, mHomeFragment).commit();
}
}, getResources().getInteger(R.integer.transition_duration));
}
else
{
getSupportFragmentManager().beginTransaction().add(R.id.dummy, mHomeFragment).commit();
}
Remove fragment
getSupportFragmentManager().beginTransaction().remove(mHomeFragment).commit();
Problem is, sometime my app has crashed when navigate from the activity contains that fragment (HomeFragment) to another activity. I tried to figure out why but still no way. I have no full error-log here because this error doesn't happen often, but the error is same like this https://android.googlesource.com/platform/frameworks/support/+/5506618c80a292ac275d8b0c1046b446c7f58836%5E!/:
IllegalStateException: Failure saving state......active HomeFragment{419494f0} has cleared index: -1
Does anyone see any problem with my code or just know how to fix this error, please help me. Thank you all in advance.
Upvotes: 0
Views: 1514
Reputation: 12477
It sounds like the runnable might be running after the activity was paused or finished. Just make sure to call handler.removeCallback on the activity onPause method to avoid the callback to the activity once it's done.
If you need to swap fragments often, you can use the FragmentTransaction hide and show methods so you avoid the initialization overhead.
Upvotes: 1