2012-11-11 26 views
2

我正在写一个使用WebServices检索数据的应用程序。最初,我有一个私人的AsyncTask类,每个活动都需要来自WebService的数据。但是我决定通过创建AsyncTask作为公共类来简化代码。所有工作正常,但我的问题是当我想访问从AsyncTask检索到的数据。多个活动的一个AsyncTask

例如,这是我的AsyncTask类。

public class RestServiceTask extends AsyncTask<RestRequest, Integer, Integer> { 

    /** progress dialog to show user that the backup is processing. */ 
    private ProgressDialog dialog; 
    private RestResponse response; 
    private Context context; 

    public RestServiceTask(Context context) { 
     this.context = context; 

     //...Show Dialog 
    } 

    protected Integer doInBackground(RestRequest... requests) { 
     int status = RestServiceCaller.RET_SUCCESS; 
     try { 
      response = new RestServiceCaller().execute(requests[0]); 
     } catch(Exception e) { 
      //TODO comprobar tipo error 
      status = RestServiceCaller.RET_ERR_WEBSERVICE; 
      e.printStackTrace(); 
     } 

     return status; 
    } 

    protected void onPreExecute() { 
     response = null; 
    } 

    protected void onPostExecute(Integer result) { 

     if (dialog.isShowing()) { 
      dialog.dismiss(); 
     } 

     switch (result) { 
     case RestServiceCaller.RET_ERR_NETWORK: 
      Toast.makeText(
        context, 
        context.getResources().getString(
          R.string.msg_error_network_unavailable), 
        Toast.LENGTH_LONG).show(); 
      break; 
     case RestServiceCaller.RET_ERR_WEBSERVICE: 
      Toast.makeText(
        context, 
        context.getResources().getString(
          R.string.msg_error_webservice), Toast.LENGTH_LONG) 
        .show(); 
      break; 
     default: 
      break; 
     } 
    } 

    public RestResponse getResponse() throws InterruptedException { 
     return response; 
    } 
} 

RestServiceCallerRestRequestRestResponse是我创建clasess。 我使用的任务是这样的:

RestRequest request = new JSONRestRequest(); 
request.setMethod(RestRequest.GET_METHOD); 
request.setURL(Global.WS_USER); 
HashMap<String, Object> content = new HashMap<String, Object>() { 
    { 
     put(Global.KEY_USERNAME, username.getText().toString()); 
    } 
}; 
request.setContent(content); 
RestServiceTask task = new RestServiceTask(context); 
task.execute(request); 

此代码工作正常和正确调用Web服务,我的问题是,当我想访问的响应。在AsyncTask我创建的方法getResponse但是当我使用它,因为它的AsyncTask仍在进行中返回一个空的对象,因此,这段代码不起作用:

//.... 
task.execute(request); 
RestResponse r = new RestResponse(); 
r = task.getResponse(); 

r将是一个空指针因为AsyncTask仍在下载数据。

我已经尝试在getResponse功能使用此代码,但它不工作:

public RestResponse getResponse() throws InterruptedException { 
     while (getStatus() != AsyncTask.Status.FINISHED); 
     return response; 
    } 

我认为与while循环线程将等到AsyncTask完成,但我取得的成就是一个无限循环。

所以我的问题是,我怎么能等到AsyncTask完成,所以getResponse方法将返回正确的结果?

最好的解决方法是使用onPostExecute方法,但由于AsyncTask被许多活动使用,我不知道该怎么做。

+0

你必须使用观察者模式! http://stackoverflow.com/a/13160409/1285331 –

回答