嘿,我是新來的Android,我有麻煩登錄頁面。我試圖連接到包含用戶名和密碼的MySQL數據庫。我試圖讓我的代碼工作,但它只是不會讓我登錄。Android與MySQL登錄頁面
這裏是我的代碼
package login.CBA;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpProtocolParams;
public class login extends Activity {
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnCancel;
private TextView lblResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etUsername = (EditText)findViewById(R.id.Username);
etPassword = (EditText)findViewById(R.id.password);
btnLogin = (Button)findViewById(R.id.login);
btnCancel = (Button)findViewById(R.id.Cancel);
lblResult = (TextView)findViewById(R.id.result);
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Username",
etUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password",
etPassword.getText().toString()));
/* String valid = "1";*/
String response = null;
try {
response =
CustomHttpClient.executeHttpPost("localhost/check.php",
postParameters);
String res = response.toString();
//res = res.trim();
res = res.replaceAll("\\s+","");
// error.setText(res);
if (res.equals("1")) {
Intent i = new Intent(getApplicationContext(), mainmenu.class);
startActivity(i);
}
else lblResult.setText("Incorrect Username or Password Entered");
}
catch (Exception e) {
etUsername.setText(e.toString());
}
}
});
}
}
和PHP代碼
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
$conn = mysql_connect('localhost', 'root', 'user');
mysql_select_db('cba');
$query = 'SELECT * FROM login WHERE username = ‘$un’ AND password = ‘$pw’';
$result = mysql_query($query) or die ('Unable to verify user because : ' .
mysql_error());
if (mysql_num_rows($result) > 0) {
echo 1;
}
else {
// print status message
echo 0;
}
?>
你得到 「錯誤的用戶名和密碼進入」 的消息? – kosa 2012-01-30 19:45:27
好吧,我已經更改了單引號,但現在在模擬器 – user1058469 2012-01-30 19:59:38
中收到'org.apache.http.NoHttpResponseException:目標服務器未能響應'消息,我們需要更加關注:PHP工作和android代碼失敗?如果您不確定,請嘗試將用戶/密碼直接發佈到php文件中並查看。那麼我們可以從那裏拿走(在你發佈確切的錯誤後)。 – alfasin 2012-01-30 21:30:14