1

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

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

这是我的代码。

@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()
4

2 回答 2

0

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

Web 连接是一种阻塞调用,这意味着您的主线程将在 onClick 上被触发,直到从服务器收到成功或失败的响应。

由于主线程在网络连接中被阻塞,您的应用程序对其他事件(例如触摸/点击或任何类型的生命周期事件)没有响应,并且也无法更新 UI。这就是为什么您的应用程序会崩溃/进度对话框中不显示更新的原因。

我建议您将AsyncTask用于任何与网络相关的任务,这样您的主线程就不会被阻塞。

于 2012-07-24T09:25:56.230 回答
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);
    }
};
于 2012-07-24T09:35:43.960 回答