Reputation: 1786
In my app I have several AsyncTasks doing http requests. If a task fails I display a DialogFragment to the user.
ErrorDialogFragment newFragment = ErrorDialogFragment.newInstance(R.string.dialog_message_error);
newFragment.show(getFragmentManager(), ConstantHandler.DIALOG_ERROR);
The problem is that the user sometimes quits the Activity or the Application before the AsyncTask is completed, causing a null pointer exception on the getFragmentManager.
My question is if there is a way to avoid this except for keeping track on if each fragment and activity is still running?
Upvotes: 2
Views: 4309
Reputation: 4787
I've had the same issues before. A reasonably good answer I saw on a blog somewhere (I've forgotten) is as follows:
Give your AsyncTasks a reference to the current context. When your app is minimised/rotated, save your AsyncTasks using onRetainNonConfigurationInstance()
and getLastNonConfigurationInstance()
. Then when your app is restarted, in onCreate()
, you can check if there is an AsyncTask passed back from getLastNonConfigurationInstance()
. If there is, set it's context to the new context of your activity. Now your AsyncTask will be able to access the new Context and complete its task.
To be thorough, you probably also want to set your context to null
in your AsyncTasks before you save them using onRetainNonConfigurationInstance()
. Then in your AsyncTask, check if the Context is null before trying to do something using it. This will stop the app crashing if the AsyncTask tries to use the context while in the background.
Upvotes: 3