当用户提交登录详细信息时启动ProgressDialog

时间:2012-07-24 09:18:47

标签: android progressdialog

我的Android应用程序具有登录功能,它正在从我的在线服务器访问用户信息。它还可以通过电子邮件确认来检测注册用户是否已激活他/她的帐户。

但问题是,我的应用程序在从数据库中检索用户详细信息时几乎关闭了。我看过一些关于ProgressDialog的视频,我不知道它是否可以正确地插入到我的程序中,请帮帮我。 / p>

这是我的代码。

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.firstscreen);

    initialise();

    bGotoRegister.setOnClickListener(new View.OnClickListener()
    {    
        public void onClick(View view)
        {
            Intent i = new Intent(getApplicationContext(), Register.class);
            startActivity(i);
        }
    });        
}

private void initialise()
{
    // TODO Auto-generated method stub
    etEmail = (EditText) findViewById(R.id.loginEmail);
    etPassword = (EditText) findViewById(R.id.loginPassword);
    bLogin = (Button) findViewById(R.id.loginSubmit);
    tvEmailError = (TextView) findViewById (R.id.loginEmailError);
    tvPasswordError = (TextView) findViewById (R.id.loginPasswordError);
    bGotoRegister = (Button) findViewById (R.id.goToRegister);

    bLogin.setOnClickListener(this);
}

public void onClick(View v) 
{
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost("http://mysite.com/login.php");
    stringEmail = etEmail.getText().toString();
    stringPassword = etPassword.getText().toString();

    try 
    {
        nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("stringEmail", stringEmail));
        nameValuePairs.add(new BasicNameValuePair("stringPassword", stringPassword));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = httpclient.execute(httppost);
        if(response.getStatusLine().getStatusCode()== 200)
        {
            entity = response.getEntity();
            if(entity != null)
            {   
                InputStream instream = entity.getContent();
                JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                String errorEmail = jsonResponse.getString("errorEmail");
                if (errorEmail != "")
                {
                    tvEmailError.setText(errorEmail);
                }else{}

                String errorPassword = jsonResponse.getString("errorPassword");
                if (errorPassword != "")
                {
                    tvPasswordError.setText(errorPassword);
                }else{}

                String inactiveAccount = jsonResponse.getString("inactiveAccount");
                if (inactiveAccount.length() != 0)
                {                       
                    AlertDialog alert = new AlertDialog.Builder(FirstScreen.this).create();
                    alert.setCancelable(false);
                    alert.setMessage("Your account is currently inactive and unusable." + "\nDo you want to send an account activation message to your email now?");
                    alert.setButton("Yes", new DialogInterface.OnClickListener()
                    {   
                        public void onClick(DialogInterface arg0, int arg1)
                        {
                            httpclient = new DefaultHttpClient();
                            httppost = new HttpPost("http://mysite.com/activate2.php");
                            stringEmail = etEmail.getText().toString();
                            stringPassword = etPassword.getText().toString();

                            try
                            {
                                nameValuePairs = new ArrayList<NameValuePair>();
                                nameValuePairs.add(new BasicNameValuePair("stringEmail", stringEmail));
                                nameValuePairs.add(new BasicNameValuePair("stringPassword", stringPassword));

                                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                                response = httpclient.execute(httppost);
                                if(response.getStatusLine().getStatusCode()== 200)
                                {
                                    entity = response.getEntity();
                                    if(entity != null)
                                    {
                                        InputStream instream = entity.getContent();
                                        JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                                        String successActivation = jsonResponse.getString("successActivation");
                                        if (successActivation.length() != 0)
                                        {
                                            //Progress Dialog here.
                                            Toast.makeText(getBaseContext(), "We successfully sent an activation message to your email account. Try to log in again after activating your account.", Toast.LENGTH_LONG).show();
                                        }
                                        else
                                        {
                                            Toast.makeText(getBaseContext(), "Sorry, we are unable to reach your email account.",Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }   
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                                Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    alert.setButton2("Not now", new DialogInterface.OnClickListener()
                    {   
                        public void onClick(DialogInterface arg0, int arg1)
                        {
                            AlertDialog alert2 = new AlertDialog.Builder(FirstScreen.this).create();
                            alert2.setCancelable(false);
                            alert2.setMessage("Are you sure you want to exit?");
                            alert2.setButton("Yes", new DialogInterface.OnClickListener()
                            {   
                                public void onClick(DialogInterface arg0, int arg1)
                                {
                                    finish();
                                }
                            });
                            alert2.setButton2("No", new DialogInterface.OnClickListener()
                            {   
                                public void onClick(DialogInterface arg0, int arg1)
                                {
                                    //Do nothing
                                }
                            });
                            alert2.show();
                        }
                    });
                    alert.show();
                }else{}

                if ((errorEmail.length()==0) && (errorPassword.length()==0)&& (inactiveAccount.length()==0))
                {                       
                    String dbEmail = jsonResponse.getString("dbEmail");
                    String dbPassword = jsonResponse.getString("dbPassword");
                    //---Store dbEmail and dbPassword to SharedPreferences---//
                    //-------------------------------------------------------//
                    Intent i = new Intent(getApplicationContext(), Construction.class);
                    startActivity(i);
                    finish();
                }

            }//if (entity!=null)..      
        }//if response()...
    }//try..
    catch(Exception e)
    {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
    }   
}//END onClick()

2 个答案:

答案 0 :(得分:0)

您正在主线程上建立HTTP连接,这是在Android中编程的一种糟糕方式。

Web Connection是一种阻塞调用,意味着您的主线程将被点击,直到服务器收到成功或失败的响应。

由于主要线程在网络连接中被阻止,您的应用程序无法响应其他事件,如Touch / tap或任何类型的生命周期事件,也无法更新UI。这就是您的应用程序崩溃/进程对话框中没有显示更新的原因。

我建议您使用AsyncTask进行任何与网络相关的任务,以免主线程被阻止。

答案 1 :(得分:0)

您正在进行网络操作在事件线程中登录和检索详细信息,而不是在事件线程之外的其他线程中或在AsyncTask中执行此操作。

按进度对话框,您可以显示正在进行某些处理。

我正在编写一个示例代码,介绍如何在程序中使用进度对话框,线程和处理程序:

public void onClick(View v) 
{
    progressDialog=ProgressDialog.show(v.getContext(), "Login",  "Logging In...." );
    Thread thread= new Thread()
    {
        public void run()
        {
             httpclient = new DefaultHttpClient();
    httppost = new HttpPost("http://mysite.com/login.php");
    stringEmail = etEmail.getText().toString();
    stringPassword = etPassword.getText().toString();

    try 
    {
        nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("stringEmail", stringEmail));
        nameValuePairs.add(new BasicNameValuePair("stringPassword", stringPassword));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = httpclient.execute(httppost);
        if(response.getStatusLine().getStatusCode()== 200)
        {
            entity = response.getEntity();
            if(entity != null)
            {   
                InputStream instream = entity.getContent();
                JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                String errorEmail = jsonResponse.getString("errorEmail");
                if (errorEmail != "")
                {
                    tvEmailError.setText(errorEmail);
                }else{}

                String errorPassword = jsonResponse.getString("errorPassword");
                if (errorPassword != "")
                {
                    Message msg= errHandler.obtainMessage();
                    msg.obj=errorPassword;
                    errHandler.sendMessage(msg);
                }else{}

                //


            }//if (entity!=null)..      
        }//if response()...
    }//try..
    catch(Exception e)
    {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
    }   
        }
    }

Handler errHandler=new Handler()
{
    public void handleMessage(Message msg)
    {
          progressDialog.dismiss();
          String strErr=(String)msg.obj;
          tvEmailError.setText(strErr);
    }
};