当我点击android模拟器上的登录按钮时,它出现在用户名文本框上。
请帮助我解决它…谢谢你的帮助~
. lang。
:android.os。NetworkOnMainThreadException
——更新7.9.2011
我把我的代码放在这里:
http://pastebin.com/EX0ArwaE -> Login.java
http://pastebin.com/WgGctGHN -> CustomHttpClient.java
首先是Android的东西:你得到这个NetworkOnMainThreadException
因为你试图在你的主应用线程上做一个HTTP请求那是UI线程。您不应该在此线程中执行任何阻塞操作。请使用AsyncTask。
我不太确定是什么导致了IllegalArgumentException
,但我猜是这一行:
response = CustomHttpClient.executeHttpPost("http://127.0.0.1/es/check.php", postParameters);
您可能已经更改了URL (localhost通常在电话上没有意义)。方案部分为http
。也许您在原始代码中有" http://..."
(注意前导空格字符)之类的东西?
关于PHP的简短说明:
$sql = 'SELECT * from people WHERE username = "' .$_POST['un'] . '" and password = "' .md5($_POST['pw']) . '"';
这就是所谓的SQL注入。
Update:这里有一些例子。没有测试,希望它能工作。
public class LoginLayout extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new LoginTask().execute(un.getText().toString(), pw.getText().toString());
}
});
}
private class LoginTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", params[0]));
postParameters.add(new BasicNameValuePair("password", params[1]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://127.0.0.1/es/check.php", postParameters);
String res = response.toString();
res = res.replaceAll("\s+","");
return res;
} catch (Exception e) {
return e;
}
}
protected void onPostExecute(Object result) {
if (result instanceof String) {
if (result.equals("1")) {
error.setText("Correct Username or Password");
} else {
error.setText("Sorry!! Wrong Username or Password Entered");
}
} else if (result instanceof Exception) {
un.setText(result.toString());
}
}
}
}