Question

I've developed an app, but a user is stating the app is crashing on them in a specific part, the code I suspect to be the culprit can be found below, but to provide you with some context. I have a fragment manager that acts as a wizard, and on the last fragment is a submit button that, when clicked, "processes" the data from all pager fragments and then redirects to a confirmation fragment, all of this happening after the submit button is clicked is done within an Async Task. Also, if it is of any consequence, I am running a progress dialog while the AsyncTask is running.

//Called from Async Task's "onPostExecute()"
private void callback()
{
    FragmentManager fragmentManager = getActivity()
            .getSupportFragmentManager();

    fragmentManager.popBackStack("fraud_report", FragmentManager.POP_BACK_STACK_INCLUSIVE);

    Fragment f =  new CompletedFragment();

    Bundle args = new Bundle();

    args.putString("id", reportToSubmit.getReferenceId());

    f.setArguments(args);

    fragmentManager.beginTransaction()
            .replace(R.id.content_frame, f, "completed").commit();

    fragmentManager.executePendingTransactions();


}
Was it helpful?

Solution

I have a guess as to what this could be, especially if it is hard to reproduce. You issue is that you are doing a FragmentTransaction after an asynchronous callback, during which any number of things can happen. Therefore you cannot guarantee where you will be in the Activity Lifecycle. The problem is Fragments and State Loss.

http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html

https://stackoverflow.com/a/17527246/1856960

Say for example, the user starts the AsyncTask, then ends the Activity, starts another one, or hits the home button. All of this will put the Activity in the background and may trigger a call to onSaveInstanceState. You cannot commit a Fragment Transaction after onSaveInstanceState is called. This is because the FragmentManager and all the state associated with it has already been bundled in onSaveInstanceState, so if the Activity is destroyed and re-created, you will lose your Fragment Transaction.

As for fixing the issue, I wish I had a good suggestion for you. You can look into FragmentTransaction#commitAllowingStateLoss but this should only be used if you are sure the potential downfalls will not negatively impact your application. See the links above for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top