这是我的第一个异步任务,它首先被调用,它从服务器获取数据,然后onPostExecute
执行其他异步任务,下载并设置图像。
private class GetData extends AsyncTask<String, Void, Void> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private String error = null;
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... progress) {
}
@Override
protected Void doInBackground(String... params) {
try {
HttpGet httpget = new HttpGet(params[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
error = e.getMessage();
cancel(true);
} catch (IOException e) {
error = e.getMessage();
cancel(true);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (error == null) {
try {
JSONObject dataDishes = new JSONObject(content);
Log.d("DISHES", dataDishes.toString());
ArrayList<DishModel> dishData = new ArrayList<DishModel>();
for (int i = 0; i < 8; i++) {
DishModel model = new DishModel();
model.setName("Company " + i);
model.setDesc("desc" + i);
//TODO: set data img
new GetImage(model).execute("http://example.com/" + (i + 1) + ".png");
dishData.add(model);
}
ListView listAllDishes = (ListView) getView().findViewById(R.id.listView);
DishRowAdapter adapterAllDishes = new DishRowAdapter(getActivity(),
R.layout.dish_row, dishData);
listAllDishes.setAdapter(adapterAllDishes);
} catch (JSONException e) {
Log.d("DISHES", e.toString());
}
} else {
Log.e("DISHES", error);
}
}
}
这是另一个异步任务,它下载图像,onPostExecute
它将图像设置为传递模型。
private class GetImage extends AsyncTask<String, Void, Void> {
private DishModel model;
private Bitmap bmp;
public getImage(DishModel model) {
this.model = model;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... progress) {
}
@Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DISHES", params[0]);
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.d("DISHES", e.toString());
}
} catch (MalformedURLException e) {
Log.d("DISHES", e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
model.setPhoto(bmp);
}
}
如果我在一个AsyncTask doInBackground(String... params)
中同时执行数据/图像下载过程,它就可以工作,但是当我将数据和图像下载拆分成单独的异步任务时,它不起作用。此外,我没有任何例外或错误。
更新:当我切换视图时图像显示..
答案 0 :(得分:0)
首先,getImage和getData是类,Java中的类名称是大写的。
从技术上讲,您可以从onProgressUpdate()
或onPostExecute()
- https://stackoverflow.com/a/5780190/1159507运行另一个AsyncTask
因此,尝试将断点放在第二个AsyncTask调用中,并调用它调用。