如何在Fragment的onDetach()中执行AsyncTask(IllegalStateException)

时间:2014-07-11 10:26:50

标签: android android-fragments android-asynctask

我有一个片段,当片段完全从片段中删除时(不仅仅是当它被添加到backStack时),我需要告诉服务器在服务器端解锁一个实体。(当片段是创建)。所以我的onDetach()方法如下:

@Override 
    public void onDetach(){

        new UnlockEntityAsyncTask().execute();
        Log.v("ResultViewFragment", "View onDetach called");

        super.onDetach();
    }

可悲的是,到网络操作开始时,片段不再附加到活动,我得到IllegalStateException:

07-11 15:55:08.600: E/AndroidRuntime(4239): java.lang.RuntimeException: An error occured while executing doInBackground()
07-11 15:55:08.600: E/AndroidRuntime(4239):     at android.os.AsyncTask$3.done(AsyncTask.java:278)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.lang.Thread.run(Thread.java:864)
07-11 15:55:08.600: E/AndroidRuntime(4239): Caused by: java.lang.IllegalStateException: Fragment ResultViewFragment{40f26e18} not attached to Activity
07-11 15:55:08.600: E/AndroidRuntime(4239):     at android.support.v4.app.Fragment.getResources(Fragment.java:603)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at android.support.v4.app.Fragment.getString(Fragment.java:625)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at com.amberroad.sigmatickettracker.screen.ResultViewFragment$UnlockEntityAsyncTask.doInBackground(ResultViewFragment.java:395)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at com.amberroad.sigmatickettracker.screen.ResultViewFragment$UnlockEntityAsyncTask.doInBackground(ResultViewFragment.java:1)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
07-11 15:55:08.600: E/AndroidRuntime(4239):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

所以我猜错了,因为我试图在没有附加到活动时执行片段的代码。我该如何克服这个问题?

修改

doInBackground的第一行使用名为mContext的Fragment(ResultViewFragment)变量,该变量在getActivity().getApplicationContext()中初始化为onCreateView()。这会导致问题吗?

1 个答案:

答案 0 :(得分:1)

您应该将应用程序上下文作为参数发送到AsyncTask构造函数。

new UnlockEntityAsyncTask(mContext.getApplicationContext());

在您的mContext已经分离时执行的第一行doInBackground。