我有一个AsyncTask类,我必须使用该变量在ImageView中显示图片。我使用jsoup库来解析html页面,问题是我无法将我的变量“bitmap”从doInBackground转换为onPostExecute方法。我该如何解决我的问题? 这是代码:
private class ParseHTML extends AsyncTask<Void, Void, Void>{
String resultTextFmt;
Bitmap bm;
@Override
protected void onPreExecute(){
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("WebMD");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params){
try{
Document document = Jsoup.connect(mURL).get();
Elements description2 = document.select("h2[class=et_pt_title]");
Log.v("Data3", description2.toString());
resultTextFmt = description2.toString();
Elements divs = document.select("img");
Log.w("DIVS_PICS", divs.toString());
Bitmap bitmap;
for (Element div : divs) {
Log.d("web Stuff",div.text());
// Element myImage = div;
String iurl;
iurl = div.absUrl("src");
Log.w("ABSurl:",iurl.toString());
URL url = new URL(iurl);
bitmap = BitmapFactory.decodeStream(url.openStream()); // I need to get this var
}
bm = bitmap;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result){
imgView.setImageBitmap(bm); // and put it here to show
textView.setText(Html.fromHtml(resultTextFmt));
mProgressDialog.dismiss();
}
}
答案 0 :(得分:1)
你需要像这样声明你的AsyncTask:
private class ParseHTML extends AsyncTask<Void, Void, Bitmap>{
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(Void... params){
Bitmap returnValue = new Bitmap();
return returnValue;
}
@Override
protected void onPostExecute(Bitmap result){
imgView.setImageBitmap(result);
}
}
如您所见,您可以在类定义中将结果值参数化为doInBackground()
的位图。这样,您还将在onPostExecute()
回调中收到此值,并在编写后处理其中的位图。
如果您想通过处理输入参数使其更加复杂,或者,例如,了解如何监控该过程,您可以获得有关AsyncTask here的官方文档。