使用php集成和线程在Android中进行用户注册


User Registration in android with php integration and Threads

我的代码有问题,无法弄清楚出了什么问题我正在尝试制作注册表并将用户名和密码提交到数据库用户名和密码并成功存储在数据库中,但问题是我无法测试它们是否已插入。我有一个响应测试仪

if(response.equalsIgnoreCase("1")){
            dialog.dismiss();
                showAlert();    
        }

但问题是dialog.dismiss();被执行而showAlert();没有执行

这是我的完整代码RegisterActivity.java

Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    b = (Button)findViewById(R.id.button1);  
    et = (EditText)findViewById(R.id.username);
    pass= (EditText)findViewById(R.id.password);
    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(RegisterActivity.this, "", 
                    "Validating user...", true);
             new Thread(new Runnable() {
                    public void run() {
                        Register();
                    }
                  }).start();               
        }
    });
}
void Register(){
    try{            
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://192.168.1.112/RegisterConnectNow.php"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>(2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
        nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
        nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        response=httpclient.execute(httppost);
        // edited by James from coderzheaven.. from here....
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);

        if(response.equalsIgnoreCase("1")){
            dialog.dismiss();
                showAlert();    
        }else {
            dialog.dismiss();
            showAlert();
        }
    }catch(Exception e){
        dialog.dismiss();
    }
}
public void showAlert(){
    new AlertDialog.Builder(this)
    .setTitle("OK")
    .setMessage("OK")
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // continue with delete
        }
     })
    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // do nothing
        }
     })
    .setIcon(android.R.drawable.ic_dialog_alert)
     .show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.register, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
public void displayToast(String s){
     Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}

这是PHP脚本

DatabaseConnectNow.php

    <?php
$hostname_localhost ="localhost";
$database_localhost ="users";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
?>

RegisterConnectNow.php

<?php
require_once 'DatabaseConnectNow.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from userstable where username = '".$username."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
 if($rows == 0) { 
 $query = "INSERT INTO userstable (username,password)
                    VALUES ('$username', '$password')";
            mysql_query($query);
            echo "1";
 }
 else  {
    echo "2"; 
}
?>

所以我正在测试响应是否为 1,那么它应该显示对话框,我尝试显示 toast,但什么都没有显示,我有一种感觉这与线程有关。

感谢帮助。

您必须为 AlertDialog 创建一个新的 Runnable,以便它紧跟在进度对话框之后。 你可以做的是这样的:

在您的public void showAlert()执行以下操作:

public void showAlert(){
    YourActivityName.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {

            new AlertDialog.Builder(YourActivityName.this)
                    .setTitle("OK")
                    .setMessage("OK")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }
    });
}