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 でこれを行う必要があります。

Progress Dialog により、進行中の処理があることを示すことができます。

プログラムで進行状況ダイアログ、スレッド、およびハンドラーを使用する方法のサンプル コードを作成しています。

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 に答える