简体   繁体   中英

Can't do ProgressDialog.show() on a Fragment

I'm developing an Android application and I have this AsynTask in a 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();
    }
}

But when I execute the task I get this error:

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)

Do you know what is happening?

Your problem might be the context you use in SendUserDatasAsynTask(Context context) .
Make sure you pass your Activity as context and not the ApplicationContext .

So inside your fragment change your asynctask's initialization to
SendUserDatasAsynTask myTask = new SendUserDatasAsynTask(getActivity()) ;

Try using the following:

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

This works when calling from the main activity, not sure about an AsyncTask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM