2011-11-30 84 views
0

我在下面的代码中收到以下错误:返回类型与AsyncTask.onPostExecute(Integer)不兼容。我试图从doInBackground任务中完成的http请求返回结果。我得到错误:类型不匹配:无法在isAvailable的返回语句中从AsyncTask转换为int。我觉得有些事情很简单,我没有做,但我无法弄清楚。Android AsyncTask(从doInBackground返回一个整数)

public int isAvailable(int position) { 
     GetIsAvailable isAvail = new GetIsAvailable(); 
     Integer nisAvail = isAvail.execute(position); // error is still here 
     return nisAvail; 

    } 

    private class GetIsAvailable extends AsyncTask<Integer,Void,Integer > { 

     @Override 
     protected Integer doInBackground(Integer...position) { 
      Bundle resBundle = new Bundle(); 
      String url = "http://www.testurl.com" 
       + position[0]+"&uname="+AppStatus.mUserName; 
      URL iuri; 
      try { 
       iuri = new URL(url); 
       URLConnection connection = iuri.openConnection(); 
       connection.setDoInput(true); 
       connection.setDoOutput(true); 
       connection.setUseCaches(false); 
       connection.setRequestProperty("Content-type", 
         "application/x-www-form-urlencoded"); 
       BufferedReader br = new BufferedReader(new InputStreamReader(
         (InputStream) connection.getContent())); 
       resBundle.putInt("isAvail", Integer.parseInt(br.readLine().trim())); 
      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      return new Integer(0); 

      } 

     @Override 
     protected Integer onPostExecute(Integer isAvail) { // Main Error here 

      return isAvail; 
     } 
+1

这可能是完全关闭基地(?哎,我在课堂上,现在,我得到了一通,右),但你不应该'返回新的整数(0)' ? – kcoppock

+0

是的,但似乎我仍然有相同的错误。 – user836200

回答

2

哦,我想我看到了问题。我认为你不能像现在这样处理这个问题。您应该在onPostExecute()方法内处理isAvail值的影响。 isAvailable()正在主线程上运行,而isAvail正在单独的线程上运行。您试图在完成完成之前返回AsyncTask的结果。

我99%确定这是问题所在。

+1

您说得对,AsyncTask根本不会返回任何内容,而且您无法按照现在的方式检索结果。结果必须在onPostExecute()上处理。 – jcxavier

+0

这是有道理的,我相信这是问题,但如何获得onPostExecute中的整数结果返回到主线程? – user836200

+0

与其以这种方式思考,不如考虑你计划用返回的Integer做什么。那么不能在'onPostExecute()'中处理呢? 'onPostExecute()'在UI线程上运行,所以如果要修改一个Activity,在这里这样做是安全的。 – kcoppock

1

这返回一个int:

return Integer.parseInt(br.readLine().trim()); 

这个返回一个int以及:

return 0; 

您必须返回一个整数:

return new Integer(br.readLine().trim()); 

return new Integer(0); 
+0

这是真的,但我仍然有相同的错误:无法从AsyncTask 转换为Integer,并且无法从AsyncTask 转换为Integer(我已更新我的代码以包含更改) – user836200

2

我相信你在找什么是

Integer nisAvail = isAvail.execute(position).get(); 

但随后的任务不再是异步的UI线程必须等待,直到完成的AsyncTask。

如果你想保持它的异步,那么你必须在onPostExecute中处理结果。

+0

+1提及AsyncTask.get(),它是可行的,但不是一个好习惯,因为在UI线程块线程执行上调用AsyncTask.get()并可能获得ANR异常。 – yorkw

-1

如果你想获得从doInBackground方法返回的值。 那么做到这一点:

Integer Value = AsyncTaskClass.execute(ParamsIfSpecified).get(); 
+0

在这里添加一些解释来描述你的答案 –

+0

我已经说明了@Unni Kris –

相关问题