[英]Android:Username and password login using httppost
我正在使用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();
}
}
}
您應該調試以檢查問題是否出在onClick或HTTP傳輸上。 在onClick內部,我個人不會檢查您的視圖。 不知道它是否有效,但我通常使用:
if(null != view)switch(view.getId()){
case R.id.btn_login: postLoginData();break;
}
您應該嘗試確定問題出在哪里,這樣很清楚需要解決的問題。 我建議您在輸入onClick之后立即添加Log.d,以查看單擊屏幕時是否調用了偵聽器。
考慮使用Log.d(TAG, message)
語句調試代碼。 可以使用“ adb logcat”或Eclipse DDMS查看日志。 這應該告訴您代碼的流程。 您還可以在eclipse中使用斷點進行調試。
另外,請勿在主循環中執行網絡I / O。 這對您的用戶來說真的很糟糕。 考慮使用AsyncTask
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.