如何在android的AsyncTask中使用进度对话框 [英] How to use progress dialog in AsyncTask in android

查看:24
本文介绍了如何在android的AsyncTask中使用进度对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要用户登录的应用程序.通过 url 登录工作正常.但是,当我添加 AsyncTask 以添加进度对话框时,该应用程序不会改变意图.代码如下:

I am developing an app which requires a user to login.The login is working ok through a url. However when i add an AsyncTask to add a progress dialog,the app does not change intent.I have tried every possible method i know in vain. below is the code:

  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)

非常感谢您的帮助.谢谢.

Help will be highly appreciated.Thanks.

推荐答案

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

no need to return current Activity instance from doInBackground because AsyncTask is inner class of Activity so you just use LoginActivity.this to start next Activity change your AsyncTask class as :

   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 文本,只需使 用户验证==假

because it's not possible to updating UI elements from doInBackground and you are trying to set textview text inside login() method instead of changing Textview text just make userverified==false

这篇关于如何在android的AsyncTask中使用进度对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆