我有这个代码来请求一个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无效时,我的程序停止,我试图显示错误消息,但我不能。请帮帮我!
非常感谢。
答案 0 :(得分:0)
请检查您的日志猫。大多数情况下,您必须获得IllegalStateException。如果是这样的话,你也必须抓住它。
答案 1 :(得分:0)
如果您想检查您的网址是有效还是无效,则需要使用网址。这是一个例子。
URL url;
try {
url = new URL(urls[0]);
HttpGet httpGet = new HttpGet(url.toString());
} catch (MalformedURLException e1) {
e1.printStackTrace();
}