DialogFragment causing nullpointer crash

前端 未结 1 797
名媛妹妹
名媛妹妹 2021-01-22 13:20

In my app I have several AsyncTasks doing http requests. If a task fails I display a DialogFragment to the user.

ErrorDialogFragment newFragment = ErrorDialogFra         


        
相关标签:
1条回答
  • 2021-01-22 14:02

    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.

    0 讨论(0)
提交回复
热议问题