我成功解析了xml,并从标签和属性中获取了文本和url。 文本我已成功设置到ListView中,但是无法将位图加载到ImageView中。我想我忘记了一些小东西,例如某个地方的转换,或者我写错了AsyncTask。
这是我的解析和AsyncTask调用:
private List<SomeItem> items = new ArrayList();
listView = findViewById(R.id.listView);
IV = findViewById(R.id.iconsrc);
ArrayList<String> list = new ArrayList<>();
try {
XmlPullParser parser = getResources().getXml(R.xml.myxml);
while (parser.next() != XmlPullParser.END_DOCUMENT) {
tagname = parser.getName();
switch (parser.getEventType()){
case XmlPullParser.START_TAG:
if (tagname != null && tagname.equals(iconsrc)){
iconsrcVALUE = parser.getAttributeValue(0);
myBitmap = new AsyncForBitmap().execute(iconsrcVALUE).get();
IV.setImageBitmap(myBitmap);
}
break;
case XmlPullParser.TEXT :
tagtext = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname != null && tagname.equals(displayname)) {
programmes.add(new SomeItem(tagtext, myBitmap));
}
break;
}
}
} catch (Throwable t) {
Toast.makeText(this,
"Error while loading xml document: " + t.toString(), Toast.LENGTH_LONG)
.show();
}
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
我的AsyncTask:
class AsyncForBitmap extends AsyncTask<String, Void, Bitmap> {
private Exception exception;
protected Bitmap doInBackground(String... urls) {
try {
URL url=new URL(urls[0]);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
也许我必须添加(覆盖)onPostExecute()方法?但是我在那里需要做什么?
我尝试过类似的方式:
protected void onPostExecute(Bitmap bitmap) {
IV.setImageBitmap(bitmap);
}
但这是错误的。
答案 0 :(得分:1)
您可以执行类似将ImageView传递到构造函数中的AsyncTask的操作。为此,请如下修改您的AsyncTask:
class AsyncForBitmap extends AsyncTask<String, Void, Bitmap> {
private final ImageView mImageView;
public AsyncForBitmap(ImageView imageView){
mImageView = imageView;
}
private Exception exception;
protected Bitmap doInBackground(String... urls) {
try {
URL url=new URL(urls[0]);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)url.getContent());
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Bitmap bitmap){
mImageView.setImageBitmap(bitmap);
}
}
然后,只需执行以下操作:
...
case XmlPullParser.START_TAG:
if (tagname != null && tagname.equals(iconsrc)){
iconsrcVALUE = parser.getAttributeValue(0);
new AsyncForBitmap(IV).execute(iconsrcVALUE);
}
break;
答案 1 :(得分:0)
尝试此代码
protected void onPostExecute(Bitmap bitmap) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}