我有这段代码来请求一个 URL 并通过 TextView 在屏幕上显示结果。这是我的代码:
public class AsyncronoustaskAndroidExample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asyncronoustask_android_example);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String serverURL = "http://androidexample.com/media/webservice/getPage.php";
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(AsyncronoustaskAndroidExample.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
protected void onPreExecute() {
uiUpdate.setText("Output : ");
}
protected Void doInBackground(String... urls) {
try {
// Server url call by GET method
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
if (Error != null) {
uiUpdate.setText("Output : "+Error);
} else {
uiUpdate.setText("Output : "+Content);
}
}
}
}
但是当 URL 无效时,我的程序停止,我试图显示错误消息但我不能。请帮我!
非常感谢。