我正在尝试通过 asynctask 类访问 url,有时,url 可能无法访问,在这种情况下应用程序崩溃,我如何防止这种情况发生,我想在 UI 上显示错误消息/Toast ..我试过实现runOnUiThread(),但没有成功。
这是我的 asynctask 类:在这种情况下,我将遇到 IOException。
public class SelectedEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee>>{
private CaptureActivity captureActivity;
public SelectedEmployeeAsyncTask(CaptureActivity activity) {
this.captureActivity = activity;
}
@Override
protected ArrayList<Employee> doInBackground(String... url) {
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.selectedEmployeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
@Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
captureActivity.display(employees);
//activity.showEmployees(employees);
//activity.setContentView(R.layout.activity_capture);
}
}
这是我的活动类,其中将调用 asynctask:
public class CaptureActivity extends Activity {
//private String url = "http://192.168.3.140:8080/EmployeeXmlDemo/EmployeeList.xml";
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
//if(employees!=null){
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
//selectedEmployeeAsyncTask = new SelectedEmployeeAsyncTask(this);
employeeAsyncTask.execute(url);
setContentView(R.layout.activity_capture);
System.out.println("Status "+employeeAsyncTask.getStatus());
//}
}