我正在使用eclipse并且已经尝试使用http请求和php脚本连接到服务器端进行登录一段时间。
问题是当我点击登录按钮时没有任何反应,我的猜测是OnClikListener存在问题,或者文本字段的数据没有发送到服务器
这是我的代码。
public class LogInActivity extends Activity implements OnClickListener
{
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(LogInActivity.this);
result = (TextView)findViewById(R.id.lbl_result);
}
public void postLoginData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/androidRegistration/login.php");
try {
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("LogInActivity", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("LogInActivity", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("LogInActivity", "TRUE");
result.setText("Login successful");
}else
{
Log.w("LogInActivity", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return total;
}
@Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
答案 0 :(得分:0)
您应该调试以检查onClick或HTTP传输是否存在问题。 在onClick内部,我个人不会检查像你的视图。不确定它是否正常工作但我通常使用:
if(null != view)switch(view.getId()){
case R.id.btn_login: postLoginData();break;
}
你应该尽量缩小问题的范围,以便明确需要修复的内容。 我建议您在输入onClick后立即添加Log.d,以查看在单击屏幕时是否调用了侦听器。
答案 1 :(得分:0)
考虑使用Log.d(TAG, message)
语句来调试代码。可以使用`adb logcat'或eclipse DDMS查看日志。这应该告诉您代码的流程。您也可以在eclipse中使用断点进行调试。
此外,请勿在主循环中执行网络I / O.它对你的用户来说真的很糟糕。考虑使用AsyncTask