2012-02-17 283 views
0

我正在使用eclipse,並嘗試了一段時間來使用http請求和php腳本來連接到服務器端進行登錄。Android:使用httppost登錄的用戶名和密碼

問題是,當我點擊登錄按鈕沒有任何反應,我的猜測是沒有與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

服務器給出的響應是什麼? (包括標題) – jmcdale 2012-02-17 17:13:11

回答

0

您應該進行調試以檢查問題是否與onClick或HTTP傳輸有關。 Inside onClick我個人不會檢查你的視圖。不知道它的工作或沒有,但我通常使用:

if(null != view)switch(view.getId()){ 
    case R.id.btn_login: postLoginData();break; 
} 

你應該儘量縮小範圍是哪裏的問題所以很清楚什麼需要修復。 我建議你在輸入onClick後立即添加Log.d,以便在單擊屏幕時查看是否調用偵聽器。

0

考慮使用Log.d(TAG, message)語句來調試您的代碼。日誌可以使用`adb logcat'或eclipse DDMS來查看。這應該告訴你代碼的流程。你也可以在eclipse中使用斷點進行調試。

另外,不要在主循環中執行網絡I/O。它對你的用戶非常不利。考慮使用AsyncTask

相關問題