警报对话框和ASync任务

时间:2011-11-24 13:26:14

标签: android android-asynctask alertdialog

我正在尝试在活动中使用警报对话框和异步任务,并收到以下错误

  

引起:java.lang.RuntimeException:无法在里面创建处理程序   没有调用Looper.prepare()

的线程

代码:

public class loginTask extends AsyncTask<Void, Void, Void> {
    public ProgressDialog loginDialog = new ProgressDialog(
            LoginActivity.this);

    @Override
    protected void onPreExecute() {
        loginDialog.setMessage("Please wait Logging in");
        loginDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        if(loginUser()) {
            loginDialog.dismiss();
            alertbox("title", "winnn", "Okay");
        } else {
            loginDialog.dismiss();
            alertbox("title", "message", "Okay");
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void unused) {
        loginDialog.dismiss();
        Intent intentHome = new Intent(LoginActivity.this,
                HomeActivity.class);
        startActivity(intentHome);
    }
}

2 个答案:

答案 0 :(得分:10)

您无法直接在doInBackground()方法中更新UI。 (是的,如果你仍想执行,那么在runOnUiThread()内的 doInBackground() 方法内写一下

否则,请在onPostExecute()方法中进行。

public class loginTask extends AsyncTask<Void, Void, Void> 
{
    public ProgressDialog loginDialog = new ProgressDialog( LoginActivity.this );
    public Boolean flag;

    @Override
    protected void onPreExecute() {
        loginDialog.setMessage("Please wait Logging in");
        loginDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        if(loginUser())
          flag = true;
        else 
          flag=false;

        return null;
    }

    @Override
    protected void onPostExecute(Void unused) {
        loginDialog.dismiss();

        if(flag)
          alertbox("title", "winnn", "Okay");
        else
          alertbox("title", "message", "Okay");
    }
}

答案 1 :(得分:1)

onPreexecute和onPostExecute是Async Task中UI部分的一部分.doInBackground是一个单独的线程,所以在doInBackground中完成的任何事情都需要以progressUpdate的形式处理

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

示例参考:Link

反映了在doInBackground流程之间需要对UI进行的任何更改。