AsyncTask onPreExecute()中的对话框

时间:2016-09-26 14:00:44

标签: android android-asynctask

在我的应用中,我使用呼叫AsyncTask-A来检查用户是否是新用户并致电AsyncTask-B以提示用户输入新密码并重置密码。我开始知道显示对话框应该在onPreExecute()上完成,然后在KSOAP上更改密码(使用doInBackground())。但是,问题是alert.show();不等待,并且 doInBackground()会立即调用,从而破坏逻辑。以下是代码的相关部分:

private class AsyncTaskPasswordResetter extends AsyncTask<String, Void, Void>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
        builder.setMessage("Please enter new password");
        final EditText input = new EditText(login.this);
        input.setText("");
        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        SoapObject request = new SoapObject("http://tempuri.org/", "ChangeParentPassword");
                        request.addProperty(MyUtils.CreateProp("Username", userName, String.class));
                        request.addProperty(MyUtils.CreateProp("Password", password, String.class));
                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11) {{dotNet = true;}};
                        envelope.setOutputSoapObject(request);
                        HttpTransportSE androidHttpTransport = new HttpTransportSE("http://hannuveda.online/default.asmx");

                        try {
                            androidHttpTransport.call("http://tempuri.org/ChangeParentPassword", envelope);
                            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                            if (response.toString().equals("OK")) {
                                setTextViewstatus("passed\n");
                            } else {
                                setTextViewstatus("failed\n");
                                isError = true;
                            }
                        } catch (Exception e) {
                            setTextViewstatus("error\n");
                            isError = true;
                        }
                    }
                }
        );
        AlertDialog alert = builder.create();
        alert.show();
        input.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
    }

    @Override
    protected Void doInBackground(String... params)
    {
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(isError)
            SetLoginButtonEnability(true);
        setTextViewstatus("wait...");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(login.this, trackbus.class);
                    intent.putExtra("UserID", userID);
                    startActivity(intent);
                }
            }, 1000);
    }
} 

3 个答案:

答案 0 :(得分:0)

为了更好地控制顺序AsyncTask,最好使用回调。

e.g。

public class LoginTask extends AsyncTask < String, Void, HttpResponse > {

private final LoginTaskCallback callback;

public LoginTask(LoginTaskCallback callback) {
    this.callback = callback;
}


@Override
protected HttpResponse doInBackground(String...params) {
    // do network stuff
}

@Override
protected void onPostExecute(HttpResponse response) {
    // just and example
    if (response.getStatus() == 200)
        callback.success();
    else
        callback.failure();
}

public interface LoginTaskCallback {
    void failure();
    void success();
}
}

然后你可以execute任务并接收回调,并在这种情况下执行以下任何操作AsyncTaskB

 new LoginTask(new LoginTask.LoginTaskCallback() {
            @Override
            public void failure() {
               // stop here smth went wrong 
            }

            @Override
            public void success() {
               // start next task
            }
        }).execute();

答案 1 :(得分:0)

1)从AsyncTask中删除UI代码。将其保留在Activity / Fragments中 2)点击按钮,调用AsyncTask,它将处理网络操作并获得对呼叫者的响应

下面的代码应该不在AsyncTask中

        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
        builder.setMessage("Please enter new password");
        final EditText input = new EditText(login.this);
        input.setText("");
        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //This invocation is explained in details given below
                        new NetworkAsyncTask(ActivityClass.this).execute();
                    }
                }
        );
        AlertDialog alert = builder.create();
        alert.show();
        input.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(), 0);

创建将采用参数的Separate AsyncTask,以便可以使用相同的处理其他请求

建议使用方法创建接口,这会将处理后的数据返回给调用者

public interface OnAsyncTaskComplition {
    public void networkResponse(Object responseObject);

}

在发送网络请求的UI类中实现此接口

class DemoActivity extends Activity implements OnAsyncTaskComplition{

    @Override
    public void networkResponse(Object responseObject) {
     // call back will come here for failure or success

    }

}

以下是为此目的的AsyncTask

class NetworkAsyncTask extends AsyncTask<Void,Boolean,Boolean>{
      Activity activity;
      Object responce;
      ProgressDialog dialog;
      public NetworkAsyncTask (Activity activity) {
         super();
         this.activity = activity;
      }
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //Show a waiting screen
            dialog = ProgressDialog.show(activity, "Please wait", "Processing.........");

        }

        @Override
        protected Boolean doInBackground(Void... params) {
         // Do all your processing here
         //assign the response to OBJECT responce
         this.responce = processedResult;
         //return true of false based on the success
         return true;//or false based on the success
        }
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            //dismiss the dialog shown for processing
            if(dialog!=null && dialog.isShowing())
              {dialog.dismiss();}
            activity.networkResponse(responce );
        }

}

答案 2 :(得分:0)

在AsyncTaskA中检查用户是否是新的,如果是,则不要运行新的AsyncTask,而是运行AlertDialog,通过它可以从用户获取数据。
onClickListener将用户数据作为参数列表传递给AsycnTaskB

相关问题