所以我用这个方法调用这个AsyncTask getValids,第一部分被记录但不是第二部分
Log.v("","entered main & 0 part I");
String[] str_validsI = new getValids().execute("main").get();
Log.v("","entered main & 0 part II");
然而,其中的第一个Log.v从未打印过,并且没有其他功能被称为
protected String[] doInBackground(String... cat){
Log.v("We are getting a HTTP Response","1");
PreExecute IS也称为
protected void onPreExecute(){
Log.v("","We're in pre execture");
//this is the last function that is printed
}
这是getValids类,永远不会调用doInBackground并且不返回任何内容,为什么?
有没有人看到什么是错的,为什么没有被调用?
public class getValids extends AsyncTask<String,Void,String[]> {
public List<String> retd = new ArrayList<String>();
private InputStream is = null;
//public List<String> getValids(String cat)
protected String[] doInBackground(String... cat){
Log.v("We are getting a HTTP Response","1");
String base_url = "http://universitytimes.ie/mobile/";
String url = null;
List<String> list = Arrays.asList("aaaa".split("\\s*"));
Log.v("We are getting a HTTP Response","2");
if (cat.equals("main")){
url = base_url;
}else{
url = base_url+cat;
}
try {
// default HTTPClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.v("We are getting a HTTP Response","The status " + httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String str_valids = sb.toString();
list = Arrays.asList(str_valids.split("\\s*,\\s*"));
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list.toArray(new String[list.size()]);
} //end do in bg
public void setResult(List<String> in){
Log.v("We are getting a HTTP Response","1");
retd = in;
}
public List<String> getResult(){
return retd;
}
protected void onPreExecute(){
Log.v("","We're in pre execture");
}
protected void onProgessUpdate(){}
protected void onPostExecute(List<String> result){
setResult(result);
}
}
答案 0 :(得分:1)
改变这个:
String[] str_validsI = new getValids().execute("main").get();
有了这个:
String[] str_validsI = null;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) { // Build.VERSION_CODES.HONEYCOMB = 11
str_validsI = new getValids().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "main").get();
} else {
str_validsI = new getValids().execute("main").get();
}
注意:使用AsyncTask
方法get()
并不是一个好主意。因为你消除了它们的本性并使它们同步。