DialogFragment导致空指针崩溃指针、DialogFragment

2023-09-07 15:51:25 作者:紫轩蝶泪

在我的应用程序,我有几个AsyncTasks做HTTP请求。 如果任务失败我显示DialogFragment给用户。

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);

的问题是,用户有时退出活动或AsyncTask的前应用程序完成时,造成在getFragmentManager一个零指示字例外。

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?

推荐答案

我以前也有同样的问题。一个相当不错的答案,我看到了一个博客的地方(我忘了)如下:

I've had the same issues before. A reasonably good answer I saw on a blog somewhere (I've forgotten) is as follows:

给你AsyncTasks引用当前上下文。当你的应用程序最小化/旋转,使用保存AsyncTasks onRetainNonConfigurationInstance() getLastNonConfigurationInstance()。然后,当你的应用程序重新启动,在的onCreate(),您可以检查是否有一个AsyncTask的传回从 getLastNonConfigurationInstance()。如果有,设置它的背景下,以你的活动的新环境。现在,你的AsyncTask将能够访问新的语境下,完成自己的任务。

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.

要彻底,你可能还需要设置你的背景下在AsyncTasks您使用它们保存在 onRetainNonConfigurationInstance()。然后在你的AsyncTask,检查上下文是试图用它做一些事情之前空。这将阻止应用程序崩溃,如果AsyncTask的尝试使用的背景下,同时在后台。

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.