Pau*_*aul 52 string android android-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);
}
}
Run Code Online (Sandbox Code Playgroud)
而我试图这样称呼它:
String output = null;
output = new getURLData().execute("http://www.domain.com/call.php?locationSearched=" + locationSearched);
Run Code Online (Sandbox Code Playgroud)
但输出变量没有获取数据,而是我收到错误:
Type mismatch: cannot convert from AsyncTask<String,Integer,String> to String
Run Code Online (Sandbox Code Playgroud)
K-b*_*llo 111
该方法execute
返回AynscTask
自身,需要调用get
:
output =
new getURLData()
.execute("http://www.example.com/call.php?locationSearched=" + locationSearched)
.get();
Run Code Online (Sandbox Code Playgroud)
这将启动一个新线程(via execute
),同时阻塞当前线程(via get
),直到新线程的工作完成并返回结果.
如果这样做,您只需将异步任务转换为同步任务即可.
但是,使用的问题get
是因为它阻塞,所以需要在工作线程上调用它.但是,AsyncTask.execute()
需要在主线程上调用.因此,尽管此代码可行,但您可能会得到一些不良结果.我还怀疑get()
谷歌未经测试,他们可能会在某个地方引入一个错误.
paw*_*eba 18
我宁愿创建回调而不是阻止UI线程.在您的类创建方法,将在数据到达时调用.例如:
private void setData(String data){
mTextView.setText(data);
}
Run Code Online (Sandbox Code Playgroud)
然后在AsyncTask中实现onPostExecute:
@Override
protected void onPostExecute(String result) {
setData(result);
}
Run Code Online (Sandbox Code Playgroud)
然后在代码中的某处执行任务:
new getURLData().execute(...
Run Code Online (Sandbox Code Playgroud)
当任务完成时,将调用setData并填充mTextView.
AsyncTask.get()将填充您的UI,因此没有理由使用AsyncTask.
归档时间: |
|
查看次数: |
76513 次 |
最近记录: |