我正在嘗試登錄到Web服務器,並且代碼正常運行,但是當我嘗試在頁面中創建日誌時,事情開始出錯。AsyncTask在setOnClickListener中執行時無法正常工作
我正在使用Eclipse Android工具提供的示例登錄頁面,如果有人想看到任何額外的代碼位。
如果我從OnClickHandler執行,那麼DefaultHttpClient似乎超時。它不返回任何東西,或者它返回「沒有同行證書」,我知道這是錯誤的。
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
...設置的東西
mAuthTask = new UserLoginTask();
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
if(attemptLogin()){
mAuthTask.execute();
}
}
});
//mAuthTask = new UserLoginTask();
//mAuthTask.execute(); // Works if called from here.
這裏的培訓相關的AsyncTask代碼:
public class UserLoginTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
Log.i(TAG,"Thread name (from preexecute) : " + Thread.currentThread().getName());
}
protected String doInBackground(String... urls) {
DefaultHttpClient client = AppHttpClient.getClient();
HttpPost httppost = new HttpPost("https://euw.leagueoflegends.com/user/login");
String result = "";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("name", "exampleusername"));
nameValuePairs.add(new BasicNameValuePair("pass", "blahblah"));
nameValuePairs.add(new BasicNameValuePair("form_id", "user_login"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.i(TAG,"Thread name (passed into doInBackground) : " + urls[0]);
Log.i(TAG,"Thread name (from doInBackground) : " + Thread.currentThread().getName());
HttpResponse response2 = client.execute(httppost);
InputStream in = response2.getEntity().getContent();
//result = readStream(in);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(final String success) {
mAuthTask = null;
showProgress(false);
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
你可以添加你的AsyncTask的完整代碼? – Hartok 2013-02-16 20:46:35