0
在這裏,我正在嘗試從服務器的響應並顯示它響應,但我沒有這樣做,響應文本不顯示在我的文字來看,insetead字符串的默認值不,請問我該如何實現自己的目標?以及爲什麼我的代碼無法完成任務。無法顯示服務器的
這裏是我的Android程序:
public class Chico extends Activity {
GrabURL grab;
TextView mRespond;
String line;
@Override
public void onCreate(Bundle savedInstanceState) {
//create the activity
super.onCreate(savedInstanceState);
//set up the layout
setContentView(R.layout.activity_chico);
mRespond = (TextView) findViewById(R.id.Respond);
mRespond.setVisibility(View.GONE);
grab = new GrabURL();
line = "line";
//set up the button for check in
Button btnin = (Button) findViewById(R.id.inbutton);
btnin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//set the values
grab.onPreExecute("TechID", Build.SERIAL);
grab.onPreExecute("Type", "Checkin");
//set the destination and send the request
grab.execute(new String[]{"http://192.168.1.150/Me/testing.php"});
//close the activity
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);
//finish();
}
});
}
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
@Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}
}
這裏是PHP文件,它只是打印一行:
<?php
print "testing";
?>
這是我第一次開發Android應用程序,所以我想問一下onPostExecute方法execu在doinbackground後自動運行? – Conrad 2012-07-28 03:58:36
是的。如果'doInBackground(...)'引發異常,或者調用['cancel(Boolean)'](http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean) ), 它不會。欲瞭解更多信息,你可能想在這裏閱讀API文檔['onPostExecute(結果)'](http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(結果))。 – 2012-07-28 04:06:13