多活动之一的AsyncTask [英] One AsyncTask for multiple Activities

查看:96
本文介绍了多活动之一的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我书面方式使用Web服务检索数据的应用程序。起初我胸有成竹地从WebService所需的数据每个活动的私人的AsyncTask 类。但我已经决定通过创建的AsyncTask 作为一个公共类,使code简单。一切工作正常,但我的问题是,当我想从的AsyncTask 访问检索到的数据。

I'm writting an app that uses WebServices to retrieve data. Initially I had a private AsyncTask class for each activity that needed data from the WebService. But I've decided to make the code simpler by creating AsyncTask as a public class. All works fine, but my problem is when I want to access the retrieved data from the 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;
    }
}

RestServiceCaller RestRequest RestResponse 是clasess的我创建。
我使用的任务是这样的:

RestServiceCaller, RestRequest and RestResponse are clasess that I've created. I'm using the task like this:

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);

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

This code works fine and is calling the web service correctly, my problem is when I want access to the response. In the AsyncTask I've created the method getResponse but when I use it, it returns a null object because the AsyncTask is still in progress, so this code doesn't work:

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

研究将是一个空指针,因为的AsyncTask 仍然在下载数据。

r will be a null pointer because AsyncTask is still downloading data.

我已经尝试使用了 GETRESPONSE 函数这个code,但它不工作:

I've try using this code in the getResponse function, but it doesn't work:

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

我想用whil​​e循环线程将等待,直到的AsyncTask 结束,但我实现了一个无限循环。

I thought that with the while loop the thread will wait until the AsyncTask finishes, but what I achieved was an infinite loop.

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

So my question is, how could I wait until AsyncTask finishes so the getResponse method will return the correct result?

最好的解决办法是使用 onPostExecute 方法,但由于的AsyncTask 所使用的许多活动,我没有线索做什么。

The best solution is use of the onPostExecute method, but because AsyncTask is used by many activities I have no clue what to do.

我试图尽力解释自己尽我所能。

I've tried explain myself as best as I could.

问候

推荐答案

尝试创建一个回调接口。这个问题的答案异步任务问题通用类?给出了很好的解释吧。

try creating a callback interface. The answer to this async task question Common class for AsyncTask in Android? gives a good explanation for it.

这篇关于多活动之一的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆