片段上无法执行ProgressDialog.show()

时间:2013-06-21 13:57:00

标签: java android android-fragments

我正在开发一个Android应用程序,我在AsynTask中有Fragment

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)

你知道发生了什么吗?

2 个答案:

答案 0 :(得分:4)

您的问题可能是您在SendUserDatasAsynTask(Context context)中使用的背景信息 确保您将Activity作为上下文传递而不是ApplicationContext

因此在你的片段中将你的asynctask的初始化改为
SendUserDatasAsynTask myTask = new SendUserDatasAsynTask(getActivity());

答案 1 :(得分:0)

尝试使用以下内容:

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

从主活动调用时,这不起作用,不确定AsyncTask。