Skip to content Skip to sidebar Skip to footer

How Can I Avoid An Illegalstateexception If I Need To Add A Fragment In Onnewintent() Or After A Run-time Change?

I'm well aware of what an IllegalStateException is and why it happens when you are trying to commit FragmentTransactions after instance state has been saved. I've read through most

Solution 1:

I've tried using commitAllowingStateLoss() but I still get the exception because my spinner Fragment is still referencing the old destroyed Activity.

your fragment was recreated after config change, ie. after user have rotated screen - your spinner fragment will be destroyed and recreated, and after onAttach it will reference new activity instance. Also all of this process is done by android on UI thread in single message, so there is no chance that your async operation callback (which should execute also on UI thread) gets executed in the middle.

I assume here you are not creating some local reference to activity inside ProgressFragment.

You could write additional logic that would make sure your commit is called in valid moment. ie. in your activity onStart set some static boolean allowCommit to true, and in onPause set it to false. Also add some static variable, searchWasFinished, and in your async callback check if allowCommit is true if so then immediately remove spinner, if not then only set searchWasFinished to true. Inside your Activity.onStart check if searchWasFinished==true and if so then remove fragment with commit. This is just an idea, probably more logic would have to be put in it.

Post a Comment for "How Can I Avoid An Illegalstateexception If I Need To Add A Fragment In Onnewintent() Or After A Run-time Change?"