如何在android中的AsyncTask中使用进度对话框

时间:2013-01-20 16:06:32

标签: android android-asynctask

我正在开发一个需要用户登录的应用程序。登录通过网址正常工作。 但是,当我添加AsyncTask来添加进度对话框时,应用程序不会改变intent。我已经尝试了所有可能的方法,我都知道是徒劳的。 下面是代码:

  package com.epolicing;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener{
    Button loginButton;
    EditText usernme,passwrd;
    TextView error;
    String username,password;
    static final int Dialog_logging_in=1;
    boolean userverified=false;

    // Session Manager Class
     SessionManager session;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login); 
        session = new SessionManager(getApplicationContext()); 
        loginButton = (Button) findViewById(R.id.loginButton);
        usernme = (EditText) findViewById(R.id.UserName);
        passwrd=(EditText) findViewById(R.id.password);
        username=usernme.getText().toString().trim();
        password=passwrd.getText().toString().trim();
        error=(TextView)findViewById(R.id.errorTextView);
        loginButton.setOnClickListener(this);
    }

     protected Dialog onCreateDialog(int id){
      Dialog dialog = null;
      switch(id){
      case Dialog_logging_in:
          ProgressDialog.show(LoginActivity.this,"","Authenticating user...");
          break;
          default:
              dialog=null;
      }
      return dialog;

     }


    public void onClick(View v) {
        switch(v.getId()){
        case R.id.loginButton:
            String user,pass;
            user=usernme.getText().toString();
            pass=passwrd.getText().toString();

            if(user.equals("")||pass.equals("")){       
                message();
            }
            else {
                new log_in().execute(this);
            }
            break;
            }

        }

    //login method
      public void login() {
                ArrayList<NameValuePair>postParameters=new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("username",usernme.getText().toString()));
                postParameters.add(new BasicNameValuePair("password",passwrd.getText().toString().trim()));

                //String valid="1";
                String response=null;
                try{
                    response=CustomHttpClient.executeHttpPost("http://10.0.2.2/epolicing/tologin.php",postParameters);
                    String res=response.toString();
                    res=res.replaceAll("\\s+","");
                    if(res.equals("0")) {
                 error.setText("Wrong password or username combination");
                    }
                    else {
                        String usern=usernme.getText().toString().trim();
                        session.createLoginSession(usern,res);
                        userverified=true;
                        //Intent intent=new Intent(LoginActivity.this,menu.class);
                        //startActivity(intent);    
                    }
                }
                catch(Exception e){
                    error.setText(e.toString());

                }

      }


      public void message(){
        Context context=getApplicationContext();
        CharSequence text="username and/or password cannot be blank";
        int duration=Toast.LENGTH_LONG;
        Toast toast=Toast.makeText(context, text, duration);
        toast.show();
    }

     private class log_in extends AsyncTask<LoginActivity,Void,LoginActivity>{
        @Override
         protected void onPreExecute(){
            showDialog(Dialog_logging_in); 
         }
        @Override
        protected LoginActivity doInBackground(LoginActivity... Params) {
            login();
            return null;
        }
        protected void onPostExecute(LoginActivity params){
            super.onPostExecute(params);
            //dismissDialog(Dialog_logging_in);
            if(userverified==true){
                Intent intent=new Intent(LoginActivity.this,menu.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                LoginActivity.this.startActivity(intent);
            }

        }


     }
}

这是日志:

01-20 19:36:53.685: E/WindowManager(1191): Activity com.epolicing.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40555c68 that was originally added here
01-20 19:36:53.685: E/WindowManager(1191): android.view.WindowLeaked: Activity com.epolicing.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40555c68 that was originally added here
01-20 19:36:53.685: E/WindowManager(1191):  at android.view.ViewRoot.<init>(ViewRoot.java:258)
01-20 19:36:53.685: E/WindowManager(1191):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-20 19:36:53.685: E/WindowManager(1191):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-20 19:36:53.685: E/WindowManager(1191):  at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.Dialog.show(Dialog.java:241)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.ProgressDialog.show(ProgressDialog.java:107)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.ProgressDialog.show(ProgressDialog.java:90)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.ProgressDialog.show(ProgressDialog.java:85)
01-20 19:36:53.685: E/WindowManager(1191):  at com.epolicing.LoginActivity.onCreateDialog(LoginActivity.java:50)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.Activity.onCreateDialog(Activity.java:2482)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.Activity.createDialog(Activity.java:882)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.Activity.showDialog(Activity.java:2557)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.Activity.showDialog(Activity.java:2524)
01-20 19:36:53.685: E/WindowManager(1191):  at com.epolicing.LoginActivity$log_in.onPreExecute(LoginActivity.java:120)
01-20 19:36:53.685: E/WindowManager(1191):  at android.os.AsyncTask.execute(AsyncTask.java:391)
01-20 19:36:53.685: E/WindowManager(1191):  at com.epolicing.LoginActivity.onClick(LoginActivity.java:71)
01-20 19:36:53.685: E/WindowManager(1191):  at android.view.View.performClick(View.java:2485)
01-20 19:36:53.685: E/WindowManager(1191):  at android.view.View$PerformClick.run(View.java:9080)
01-20 19:36:53.685: E/WindowManager(1191):  at android.os.Handler.handleCallback(Handler.java:587)
01-20 19:36:53.685: E/WindowManager(1191):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-20 19:36:53.685: E/WindowManager(1191):  at android.os.Looper.loop(Looper.java:123)
01-20 19:36:53.685: E/WindowManager(1191):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-20 19:36:53.685: E/WindowManager(1191):  at java.lang.reflect.Method.invokeNative(Native Method)
01-20 19:36:53.685: E/WindowManager(1191):  at java.lang.reflect.Method.invoke(Method.java:507)
01-20 19:36:53.685: E/WindowManager(1191):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-20 19:36:53.685: E/WindowManager(1191):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-20 19:36:53.685: E/WindowManager(1191):  at dalvik.system.NativeStart.main(Native Method)

帮助将受到高度赞赏。谢谢。

1 个答案:

答案 0 :(得分:14)

无需从doInBackground返回当前的Activity实例,因为AsyncTask是Activity的内部类,因此您只需使用LoginActivity.this启动下一个Activity,将AsyncTask类更改为:

   private class log_in extends AsyncTask<String,Void,String>{
        ProgressDialog pDialog;
        @Override
         protected void onPreExecute(){
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Authenticating user...");
            pDialog.show();
         }
        @Override
        protected String doInBackground(String... params) {
            login();
            return null;
        }
        protected void onPostExecute(String params){
            super.onPostExecute(params);
            pDialog.dismiss();
            if(userverified==true){
                Intent intent=new Intent(LoginActivity.this,menu.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                LoginActivity.this.startActivity(intent);
            }
           else{
               error.setText("Wrong password or username combination");
            }

        }

     }

因为无法从doInBackground更新UI元素,而您尝试在login()方法中设置textview文本而不是更改Textview文本,只需创建userverified==false