"Failure Delivering Result " - onActivityForResult
Solution 1:
First of all, you should read my blog post for more information (it talks about why this exception happens and what you can do to prevent it).
Calling commitAllowingStateLoss()
is more of a hack than a fix. State loss is bad and should be avoided at all costs. At the time that onActivityResult()
is called, the activity/fragment's state may not yet have been restored, and therefore any transactions that happen during this time will be lost as a result. This is a very important bug which must be addressed! (Note that the bug only happens when your Activity
is coming back after having been killed by the system... which, depending on how much memory the device has, can sometimes be rare... so this sort of bug is not something that is very easy to catch while testing).
Try moving your transactions into onPostResume()
instead (note that onPostResume()
is always called after onResume()
and onResume()
is always called after onActivityResult()
):
private boolean mReturningWithResult = false;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mReturningWithResult = true;
}
@Override
protected void onPostResume() {
super.onPostResume();
if (mReturningWithResult) {
// Commit your transactions here.
}
// Reset the boolean flag back to false for next time.
mReturningWithResult = false;
}
This might seem a little weird, but doing this sort of thing is necessary to ensure that your FragmentTransaction
s are always committed after the Activity
's state has been restored to its original state (onPostResume()
is guaranteed to be called after the Activity
's state has been restored).
Solution 2:
This is similar to the @Alex Lockwood answer but using a Runnable
:
private Runnable mOnActivityResultTask;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mOnActivityResultTask = new Runnable() {
@Override
public void run() {
// Your code here
}
}
}
@Override
protected void onPostResume() {
super.onPostResume();
if (mOnActivityResultTask != null) {
mOnActivityResultTask.run();
mOnActivityResultTask = null;
}
}
In case you're running Android 3.0 and above with lambdas, use this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mOnActivityResultTask = () -> {
// Your code here
}
}