2013-06-21 79 views
1

我開發一個Android應用程序,我有這個AsynTaskFragment無法在片段做ProgressDialog.show()

private class SendUserDatasAsynTask extends AsyncTask<User, Void, String> 
{ 
    private Context mContext; 
    private ProgressDialog loadingDialog; 

    SendUserDatasAsynTask(Context context) 
    { 
     this.mContext = context; 
    } 

    @Override 
    protected void onPreExecute() 
    { 
     loadingDialog = new ProgressDialog(mContext); 
     loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     loadingDialog.setMessage(getString(R.string.dialog_message_sending_user_data)); 
     loadingDialog.setCancelable(false); 
     loadingDialog.show(); 

     super.onPreExecute(); 
    } 
    @Override 
    protected String doInBackground(User... users) 
    { 
     return SpringController.sendUserPersonalData(users[0]); 
    } 

    protected void onPostExecute(String result) 
    { 
     loadingDialog.dismiss(); 
     Toast.makeText(MSDApplication.getAppContext(), result, Toast.LENGTH_LONG).show(); 
    } 
} 

但是,當我execute任務我得到這個錯誤:

06-21 13:52:42.559: E/AndroidRuntime(513): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 
at android.view.ViewRoot.setView(ViewRoot.java:509) 
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177) 
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 
at android.app.Dialog.show(Dialog.java:241) 
at com.mycompany.mxt.fragments.UserProfileFragment$SendUserDatasAsynTask.onPreExecute(UserProfileFragment.java:635) 
at android.os.AsyncTask.execute(AsyncTask.java:391) 
at com.mycompany.mxt.fragments.UserProfileFragment.sendDataToWebService(UserProfileFragment.java:588) 
at com.mycompany.mxt.fragments.UserProfileFragment.onAcceptUserProfileClick(UserProfileFragment.java:477) 

你知道發生了什麼嗎?

+0

你試過'保護無效onPreExecute(視圖v)'?也許它不會工作,但很多次,這是錯誤。 – Federico

+0

對不起,我不明白你的評論。 – VansFannel

+0

你確定你的上下文沒有空嗎? – tyczj

回答

4

您的問題可能是您在SendUserDatasAsynTask(Context context)中使用的上下文。
確保您將Activity作爲上下文傳遞,而不是ApplicationContext

所以在你的片段裏你的asynctask的初始化更改爲
SendUserDatasAsynTask myTask = new SendUserDatasAsynTask(getActivity());

0

嘗試使用以下:

Dialog.show(getFragmentManager(), "TAG"); 

從主要活動打電話時,不知道的的AsyncTask這工作。