I am trying to replace fragment
in onActivityResult()
but it always gives me error of java.lang.illegalStateException.
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1377)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1395)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime: at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime: at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
12-29 18:50:21.455 5554-5554/com.package E/AndroidRuntime: at .virtualClass.VirtualPurchaseFragment.dealWithSuccessfulPurchase(VirtualPurchaseFragment.java:161)
Here is my onActivityResult
code
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = new VirtualListFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
We can call startActivityForResult directly from Fragment but actually mechanic behind are all handled by Activity. Once you call startActivityForResult from a Fragment, requestCode will be changed to attach Fragment's identity to the code.
onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.
FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.
The android startActivityForResult method, requires a result from the second activity (activity to be invoked). In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.
Finally found the solution, fragment can not be swapped or replaced in onActivityResult()
We need to put this code in Handler
or in OnResume()
Solution :
private boolean change_fragment=false;
OnActivityResult() Code
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
change_fragment=true;
}
OnResume() code
@Override
public void onResume() {
super.onResume();
if(change_fragment)
{
change_fragment=false;
Fragment fragment = new VirtualListFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With