我目前正在使用asynctask加载图像。我参考了一个示例类。但是,该位图结果为空。为什么是这样,我该如何解决这个问题?谢谢。代码如下所示。使用asyncTask在android中的列表视图中加载图像
package com.example.json;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
class ImgAdapter extends AsyncTask<Object, Void, Bitmap> {
private ImageView imv;
private String path;
public ImgAdapter(ImageView imv) {
this.imv = imv;
this.path = imv.getTag().toString();
}
@Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + path);
if (file.exists()) {
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if (!imv.getTag().toString().equals(path)) {
/*
* The path is not same. This means that this image view is handled
* by some other async task. We don't do anything and return.
*/
return;
}
if (result != null && imv != null) {
Log.i("test","success");
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
} else {
Log.i("test","result=" + String.valueOf(result == null)); //result is null here
Log.i("test","imv=" + String.valueOf(imv == null));
Log.i("test","fail");
imv.setVisibility(View.GONE);
}
}
}
如何ListView控件适配器拨打:
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView thumbnail = (ImageView) arg1.findViewById(R.id.imageView1);
ShopEntry entry = getItem(arg0);
thumbnail.setTag(entry.image_url);
new ImgAdapter(thumbnail).execute();
return arg1;
}
检查此链接。 http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android –
感谢我现在读它 – user782104
不是传递的ImageView的任务,你只要需要用返回的图像填充适配器中的数据集,然后在getView中相应地更改图像。以上实现是buggy –