这是我的以下 AsyncTask
类代码,用于为 RecyclerView
下载图像。
public class MyDownloadImageAsyncTask extends AsyncTask<String, Void,Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public MyDownloadImageAsyncTask(ImageView imv) {
imageViewReference = new WeakReference<ImageView>(imv);
}
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap bitmap = null;
for (String url : urls) {
bitmap = MyUtility.downloadImage(url);
/*if (bitmap != null) {
mImgMemoryCache.put(url, bitmap);
}*/
}
return bitmap;
}
protected void onPostExecute(Bitmap bitmap){
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
我这样在我的适配器
中调用AsyncTask
:
MyDownloadImageAsyncTask task = new MyDownloadImageAsyncTask(holder.vIcon);
task.execute(new String[] {(String)movie.get("image")}););
每次运行该应用程序时都会崩溃。下载图像的 URL 在 ArrayList
中。
我猜我在调用 AsyncTask
时犯了这个错误,但我想不出解决方案。
最佳答案
改变这个
public MyDownloadImageAsyncTask(ImageView imv) {
imageViewReference = new WeakReference(imv);
}
对此
public MyDownloadImageAsyncTask(ImageView imv) {
imageViewReference = new WeakReference<ImageView>(imv);
}
这是我使用的代码,效果很好
class LoadImage extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public LoadImage(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) {
try {
return downloadBitmap(params[0]);
} catch (Exception e) {
// log error
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.ic_launcher);
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
下面是我如何从我的 ADAPTER
new LoadImage(holder.itemImage).execute(IMAGE_URL);
分别针对每个 URL。
如果对您有帮助,请尝试一下。
关于java - 使用 RecyclerView 的 asynctask 在 android 中下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041100/