如何从AsyncTask取回字符串? [英] How to get a string back from AsyncTask?

查看:69
本文介绍了如何从AsyncTask取回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class getURLData extends AsyncTask<String, Integer, String>{

@Override
protected String doInBackground(String... params) {
    String line;
    try {  
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(params[0]);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        line = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    } catch (MalformedURLException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    } catch (IOException e) {
        line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
    }
    return line;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
}

}

我正试图这样称呼它:

String output = null;
output = new getURLData().execute("http://www.domain.com/call.php?locationSearched=" + locationSearched);

但是输出变量没有获取数据,相反,我得到了一个错误:

But the output variable isn't getting data, instead I am getting an error:

Type mismatch: cannot convert from AsyncTask<String,Integer,String> to String

推荐答案

方法execute返回AynscTask本身,您需要调用get:

The method execute returns the AynscTask itself, you need to call get:

output =
    new getURLData()
        .execute("http://www.example.com/call.php?locationSearched=" + locationSearched)
        .get();

这将启动一个新线程(通过execute),同时阻塞当前线程(通过get),直到完成新线程的工作并返回结果为止.

This will start a new thread (via execute) while blocking the current thread (via get) until the work from the new thread has been finished and the result has been returned.

如果执行此操作,则只需将 async 任务转换为 sync 任务即可.

If you do this, you just turned your async task into a sync one.

但是,使用get的问题在于,由于阻塞,因此需要在辅助线程上调用它.但是,需要在主线程上调用AsyncTask.execute().因此,尽管此代码可以工作,但您可能会得到一些不良结果.我还怀疑get()是否已由Google测试不足,并且他们很可能在此过程中的某个地方引入了错误.

However, the problem with using get is that because it blocks, it needs to be called on a worker thread. However, AsyncTask.execute() needs to be called on the main thread. So although this code could work, you may get some undesired results. I also suspect that get() is under-tested by Google, and it is possible that they introduced a bug somewhere along the line.

参考: AsyncTask.get

这篇关于如何从AsyncTask取回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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